wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes non-static variable cl cannot be referenced from a static context Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "non-static variable cl cannot be referenced from a static context" Watch "non-static variable cl cannot be referenced from a static context" New topic
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: 128
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]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: non-static variable cl cannot be referenced from a static context
 
Similar Threads
Polymorphic Method Call
generics
Marcus mock exam 2 (quest. #32)
static method calls to nonstatic methods
non-static variable this cannot be referenced from a static context