Polymorphism and inheritance in Java with static methods of abstract class

user1107888 :

I was going through the sample questions of Java 8 Programmer I exam on Oracle website and came across the following question:

abstract class Writer {
  public static  void write() {
    System.out.println("Writing...");
  }
 }
class Author extends Writer {
public static void write() {
       System.out.println("Writing book");
    }
 }
class Programmer extends Writer {
   public static void write() {
     System.out.println("Writing code");
   }
public static void main(String[] args) {
  Writer w = new Author();
   w.write();//What would be the ouput here?
    }
 }

The correct answer is that the method of the abstract class is called.

Now, my understanding was that in polymorphism, if a variable of type parent class contains a reference to an object of subclass, then the method of the subclass will be called.

Therefore, am I understanding right that in case of a static function, the method of the of the class whose variable contains the refrence would be called?

GhostCat salutes Monica C. :

There is no polymorphism for static methods.

The compiler decides at compile time which method is going to be invoked.

It sees that w is a Writer, and it does neither know or care that the actual instance will be of that specific sub class at runtime. The compiler could know it sometimes, but Java takes the easy path here.

That is one of the reasons why you are really careful about using static methods in real world production code: doing so means sacrificing one of the essential elements of OOP.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92704&siteId=1