Link to home
Start Free TrialLog in
Avatar of Cat75
Cat75

asked on

Compilation error

Hi!
Does anyone know what this compilation error means?

"StudentRegister.java:14: non-static variable this cannot be referenced from a static context
                                Car c = new Car();"
                                        ^


(Car is a second class in my program)
                                           
Avatar of Peter Kwan
Peter Kwan
Flag of Hong Kong image

Can you please post code of the section of your StudentRegister class that causes the problem?
Sorry, can you please show the code of your Car class (not the StudentRegister class), especially the constructor if you have it?
Avatar of cyberfrank
cyberfrank

The problem is that you can not use "this" variable in the static method. Static means static content for the all objects instantiated for the given class, so there is no meaning of "this". The "this" variable can be only used inside of non-static method of the instantiated object.
I am sure, that You try to call some static method from the Car() constructor and that static method used "this" variable.

BR,

Cyberfrank
I think the problem might be that Car is an inner class and can be constructed only with a this object. You put the code to construct Car in a static method, which cannot refer to "this".
For example:
class Main{
class Car{
}
public static void test(){
Car c = new Car();
}
}

I still don't understand why the error started at c, not Car(). Maybe it's a different problem. Post your code, please.
Just guessing,
daitt
ASKER CERTIFIED SOLUTION
Avatar of Senthilb
Senthilb

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Senthilb:
1. I said about this already in my comment.
2. This will cause "cannot resolve symbol" error, not the error Cat75 said.
3. This is Java, not C. The class declaration can be anywhere.

Cat75: what is the answer for your question?
Avatar of Cat75

ASKER

Car was an inner class. I chose the explanation that I understood the best. Sorry :/
Are you sure you understood the problem?