• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about static methods.

 
Aki Mohan
Ranch Hand
Posts: 99
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Mala Gupta's book it's written "You can't override the static method in a derived class, but you can redefine them.". By redefine does it mean you can overload the method or does it mean something else?

Thanks
Aakash
 
E Armitage
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create a new static method in a sub class with the same signature as a static method in the parent class. It's not overloading because with overloading you get two methods with different parameters. Here you just end up with one method.
 
Krishna Kanth
Ranch Hand
Posts: 49
1
Chrome Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That does not qualify as overriding?
because when you call the static method with parent class handle but child class object, method from parent class gets executed?

hmm, new stuff.
 
Aki Mohan
Ranch Hand
Posts: 99
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah, then isn't that overriding the static method? but again static methods can't be overridden because it's static... oh I'm so confused.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can only override a method if the method is inherited. That's why e.g. a private method can never be overridden (because it's not inherited). There is a distinction between instance methods (which can be inherited) and class (static) methods which are not inherited:
  • An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
  • If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.


  • More info and an example of the distinction between instance and class methods when it comes to overriding can be found in The Java Tutorial.
     
    Aki Mohan
    Ranch Hand
    Posts: 99
    Eclipse IDE Firefox Browser Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Aha thank you, I got this I guess. Please let me know if I understood wrong.

    So, if we go through the code.

    Animal.testClassMethod takes precedence over the Cat method.
    Cat.testClassMethod takes precedence over the Animal method.

    It kind of follows the overloading rule, doesn't it?
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic