File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: accessing a static method
 
Similar Threads
interface again
Quick Question
can anyone explain me this?
Polymorphism question
Kindly explain me the difference between inheritance and instantiation