This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes accessing a static method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "accessing a static method" Watch "accessing a static method" New topic
Author

accessing a static method

kavundamani senthil
Greenhorn

Joined: Feb 28, 2008
Posts: 16
In the program below i'm accessing the staticmethod with the instance of the class which is incorrect and has to throw an error. But it compiles fine and gives the output also correctly why is that so ?

public class example {
public static void main (String [] args) {
Animal a = new Animal();
a.num=20;
a.somemethod();
System.out.println("a.num is 20"+a.num);
}
}
class Animal {
static int num=10;
public void eat() {
System.out.println("Generic Animal Eating Generically");
}
static void somemethod()
{
System.out.println("xxx");
System.out.println("this is somemethod");
}
}
Prabhat Gupta
Ranch Hand

Joined: Jan 22, 2008
Posts: 135
As static method or variable is a for whole class rather than a particular object .Hence we can access the static method by using the object reference of that class .
Hrishikesh Maluskar
Ranch Hand

Joined: Jun 19, 2008
Posts: 115
this is just a syntax trick..the refrence of any object is substituted with the respective class name


SCJP 1.5
www.licexpadvice.com
kavundamani senthil
Greenhorn

Joined: Feb 28, 2008
Posts: 16
so can we conclude that staticmethods can always be called with instances of their classes apart from calling them with their class names ???
Hrishikesh Maluskar
Ranch Hand

Joined: Jun 19, 2008
Posts: 115
Yes Definitely
kavundamani senthil
Greenhorn

Joined: Feb 28, 2008
Posts: 16
thanks a lot Hrishikesh and Prabhat.
 
 
subject: accessing a static method