• Post Reply Bookmark Topic Watch Topic
  • New Topic

static methods question  RSS feed

 
shashank beerla
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods executes at compile time then it executes before the object construction (as they get constructed during run time). But in our main method we create a class object and invoke class methods right . How does this happen when the method execution is happening at compile time it should throw an exception for object construction. Can you explain

public class animal {

public void behaviour() {
System.out.println("I am a dog");
}

}

public class Tiger {
public static void main(String[] args) {
Animal ani = new Animal(); // here we are construction animal object which gets created runtime. How come static method gets executed then? ani.behaviour();

}
}

according to this I believe static methods executes at run time . In that case we should be able to override the static methods right?
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No methods are ever executed by the compiler. They are all executed at run time by the JVM.
 
shashank beerla
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok then in that case what makes static so special that it cannot be overriden by the sub class
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul has already answered one of your assumptions.

On your second point, static methods cannot be overridden as they belong to a class, not an instance of a class (i.e. an object).
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!