• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
reply
    Bookmark Topic Watch Topic
  • New Topic