| Author |
non-static variable cl cannot be referenced from a static context
|
Preetham M
Greenhorn
Joined: Sep 18, 2002
Posts: 12
|
|
Hi All: Im have a question on referencing a class within a static method. I have the below code: public class Main { A atest; public static void main(String[] argv) { atest = new A(); } } class A { int i; } This code does not comile, it gives the error: non-static variable cl cannot be referenced from a static context. however i move A atest; inside main(),like: public static void main(String[] argv) { A atest; atest = new A(); } i get no comilation error. Could somebody tell me why. Appreciate the help. thanks, Preetham.
|
 |
Eureka Jana
Greenhorn
Joined: Sep 04, 2002
Posts: 18
|
|
Hi Preetham, Methods declared as static has some restrictions. 1.It can call only other static methods 2.It can only access static data. 3.It cannot refer to this or super. Thanks, Jana
|
 |
Darryl Failla
Ranch Hand
Joined: Oct 16, 2001
Posts: 127
|
|
In the first example, atest is an instance attribute of class Main. This variable only exists if Main is instantiated (Main m = new Main()). Static methods exist without an instance of Main. Therefore it would make no sense to allow static methods to access instance attributes. In the second example, atest is a variable declared inside the method main(). Therefore it exists from declaration through the life of the method. Any method has access to variables declared within them.
|
Darryl Failla
Sun Certified Java 2 Programmer
|
 |
Dirk Schreckmann
Sheriff
Joined: Dec 10, 2001
Posts: 7023
|
|
Preetham M, Welcome to JavaRanch! We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy. Thanks Pardner! Hope to see you 'round the Ranch!
|
[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
|
 |
 |
|
|
subject: non-static variable cl cannot be referenced from a static context
|
|
|