Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

accessing a static method

 
kavundamani senthil
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is just a syntax trick..the refrence of any object is substituted with the respective class name
 
kavundamani senthil
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Definitely
 
kavundamani senthil
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot Hrishikesh and Prabhat.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic