Java中的多态和继承与抽象类的静态方法 [英] Polymorphism and inheritance in Java with static methods of abstract class

查看:60
本文介绍了Java中的多态和继承与抽象类的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Oracle 网站上 Java 8 Programmer I 考试的样题,并遇到以下问题:

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?

推荐答案

静态方法没有多态性.

编译器在编译时决定要调用哪个方法.

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

它看到 w 是一个 Writer,它既不知道也不关心实际实例在运行时是否属于该特定子类.编译器有时可能知道它,但 Java 在这里采用了简单的方法.

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.

这就是您在现实世界的生产代码中非常小心地使用静态方法的原因之一:这样做意味着牺牲 OOP 的基本要素之一.

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.

这篇关于Java中的多态和继承与抽象类的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆