• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding static methods

 
Douglas Cyporyn
Greenhorn
Posts: 21
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe my question hinges on the definition of "override".

I know the override rule about static methods to be as follows:
  • static methods cannot be overridden by non-static methods
  • non-static methods cannot be overridden by static methods


  • So, okay. We can override a static method with another static method. Great. But in doing so we lose the polymorphic behavior because the overriding static method only "hides" or "shadows" method in the super class.

    Consider the following code:


    We do not get the TestThisClass behavior in the ov.write() line. I understand this is because the ov reference variable is of type TestOvClass, and since the write method is static on that class, the JVM executes write as if it were TestOvClass.write() instead of running the method on the TestThisClass object the variable is referring to.

    First, am I thinking of this in the right way?

    Next, can we still say the method is overridden even if we do not get the polymorphic behavior? Is overriding merely a question for the compiler? If so then we can say yes, the compiler allows the override. Or is override a question for execution where we expect to benefit from polymorphism?

    I can just imagine an exam question that would ask if the write method is overridden in TestThisClass. My response at this point is "yes, and no".

    Thanks!
    Doug
     
    Jelle Klap
    Bartender
    Posts: 1952
    7
    Eclipse IDE Java
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Referring to this as overriding is indeed not correct. The correct term would be hiding, as you said.
    Your response should be a resounding "no".
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Likes 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Overriding ONLY applies to instance methods, NOT to variables or static methods. But you can hide/shadow variables and/or static methods.

    Douglas Cyporyn wrote:I can just imagine an exam question that would ask if the write method is overridden in TestThisClass. My response at this point is "yes, and no".

    Just select the "No" radio button (because you learnt at CodeRanch that only instance methods can be overridden ) and you can confidently move on to the next question!
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic