简体   繁体   English

Java中的多态性和继承与抽象类的静态方法

[英]Polymorphism and inheritance in Java with static methods of abstract class

I was going through the sample questions of Java 8 Programmer I exam on Oracle website and came across the following question: 我在Oracle网站上查看了Java 8 Programmer I考试的示例问题,并遇到了以下问题:

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? 因此,我理解正确的情况是,在静态函数的情况下,将调用其变量包含refrence的类的方法?

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. 它看到w是一个Writer,它既不知道也不关心实际实例在运行时是否属于该特定子类。 The compiler could know it sometimes, but Java takes the easy path here. 编译器有时可以知道它,但Java在这里采取了简单的方法。

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. 这就是为什么在实际生产代码中使用静态方法非常小心的原因之一:这样做意味着牺牲OOP的一个基本元素。

Nope, you can't override static methods in a subclass, so there's no polymorphic runtime lookup of the method. 不,你不能覆盖子类中的静态方法,因此没有方法的多态运行时查找。 Static methods have no interaction with instance fields/methods of the class, so making a call to a static method dependent on a particular instance/subclass wouldn't make sense. 静态方法与类的实例字段/方法没有交互,因此调用依赖于特定实例/子类的静态方法是没有意义的。

It's easier to think of static methods as just utility/library methods. 将静态方法视为实用程序/库方法更容易。 And they are contained within classes just for the purpose of organization. 它们只是出于组织目的而包含在类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM