• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

non-static variable cl cannot be referenced from a static context

 
Preetham M
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic