• 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
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Help on Static property

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
HI all,

I have a small doubt regarding statics in JAVA. Consider the following
code.

public Class A
{
int x=10;

void printX()
{
System.out.println ("x is :" + x);
}
public static void main()
{
printX();
}

}

This results in a Compiler error, since the compiler detects that the
non-static ( uses instance variables) method printX() is used in static
context (static void main()). This is OK.

Using the same concept the following code must also report a Compiler
error. But it works

public Class A
{
int x=10;

void printX()
{
System.out.println ("x is :" + x);
}
public static void main()
{
Class a = new A();
a.printX(); // works fine ???
}

}

Can anyone please explain how ?

Regards,
Sarathy
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by sarathy:
Using the same concept the following code must also report a Compiler
error. But it works


No, this is not the same. You cannot access instance members (variables or methods) from a static method (such as main(...)), because there is no current instance in a static method.

In your second piece of code, you are creating an instance of class A, and it's perfectly allright to invoke an instance method on that instance.
 
Paddy spent all of his days in the O'Furniture back yard with this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic