• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Abstract method cannot be static

 
Roger Zhao
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Who can tell me why it is true that "Abstract method cannot be static."
Thanks a lot!
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi roger,
i'll first enumerate some facts,
1. abstract method is the one which is not implemented in a particular class and so it must be implemented by the child class.
2. now, if there is any abstract method then the class must be abstract
3. we can't instantiate an abstract class. we must subclass it to a concrete class
4. static methods can be accessed by a class name w/o creating an instance of the class
5. static methods can't be overridden, they can only be shadowed
considering these facts, if v want to declare a abstract static method in a class then what happens?
1. that method won't have definition as its abstract
2. as it is static it must be accessible via just the class name
here there is a problem in our case. why? because we can't invoke a method that has no implementation. right? and the compiler knows that there is no possible subclass of the abstract class that might have implemented that method because the method is static and fact 5 from the above list constraints that static method can't be overridden. here jvm always invokes a method from the reference type declaration rather than runtime type.
so compiler gives us the error if we try to declare abstract static method.
okay try this,

the output is,
Parent.print1()
Child.print1()
as v see here even if the 'p' is of type Child() it invoked method of Parent because print1() is static and 'p' is of ref type Parent in the declaration. now, if we make print1() abstract in Parent then what happens to the above program? it won't work. right? because it will try to invoke print1() in Parent class which is not defined.
hope i am able to help a little.
regards
maulin
 
Roger Zhao
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's useful enough, thanks.
 
Jason Dobies
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way to look at it is from the Object Oriented point of view. An abstract is somewhat like an interface insofar as it defines a "contract" of what the object is obligated to do. An abstract method is saying "the object can do this". Static methods belong to the class, not the object, so there's no custom implementation of a method for a particular object. It's annoying because there have been many times I wanted an interface to implement a static method, but from a pure OO point of view, it doesn't make sense that way.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic