简体   繁体   English

调用抽象类的抽象方法

[英]Calling abstract method of a Abstract class

When we call an abstract method of a abstract class from its constructor it returns null.当我们从抽象类的构造函数调用抽象类的抽象方法时,它返回 null。 Why?为什么?

abstract class OverloadStaticMethod {
    OverloadStaticMethod(){
        doSubStuff();
    }
    abstract void doSubStuff();
    public static void main(String args[]) {
        new ParentClass();
    }
}
public class ParentClass extends OverloadStaticMethod {
    String s = "Hello world";

    void doSubStuff() {
        System.out.println(s);
    }
}

Output:输出:

null

Image a field that is defined like this:图像定义如下的字段:

public class Example {
    private long mark = System.currentTimeMillis();
}

That should make clear that the initializing expression used for a field is just code , and code needs to be executed at some point.这应该表明用于字段的初始化表达式只是 code ,并且代码需要在某个时候执行。 "Hello World" seems like a constant expression, but it doesn't count here (there are rules; in particular, you'd have to make s static and final for it to count as a constant). "Hello World"似乎是一个常量表达式,但在这里不算数(有规则;特别是,您必须将 s 设为 static 和 final 才能将其计为常量)。

The simple explanation is that the line of code that assigns "Hello World" to variable s has not executed yet, because execution runs in reverse order.简单的解释是,将"Hello World"赋给变量s那行代码还没有执行,因为执行的顺序是相反的。 When you have class GrandParent , class Parent extends GrandParent and class Child extends Parent , execution is:当你有class GrandParentclass Parent extends GrandParentclass Child extends Parent ,执行是:

  • First, GrandParent's initializing expressions and initializers.首先,GrandParent 的初始化表达式和初始化器。
  • Then, GrandParent's constructor.然后,GrandParent 的构造函数。
  • Then, Parent's initializing expressions and initializers.然后,Parent 的初始化表达式和初始值设定项。
  • Then, Parent's constructor.然后,Parent 的构造函数。
  • Then, Child's initializing expressions and initializers.然后,Child 的初始化表达式和初始值设定项。
  • Then, Child's constructor.然后,Child 的构造函数。

The general fix is to never call overridable methods in any constructor.一般的解决方法是永远不要在任何构造函数中调用可覆盖的方法。 If you want 'substuff' as a concept, introduce an init() method (generally constructors shouldn't do much except do some validation of parameters and store them, this is one of many reasons for why that is the general style advice), or possibly have the result of substuff be passed in as argument to the constructor of the parent class.如果您想要“substuff”作为一个概念,请引入一个init()方法(通常构造函数除了对参数进行一些验证并存储它们之外不应该做太多事情,这是为什么这是一般样式建议的众多原因之一),或者可能将 substuff 的结果作为参数传递给父类的构造函数。

NB: Note that 'overload a static method' is an impossibility in java.注意:请注意,“重载静态方法”在 Java 中是不可能的。 static methods do not partake in dynamic dispatch at all, and 'overload' as a concept applies to dynamic dispatch.静态方法根本不参与动态调度,“重载”作为一个概念适用于动态调度。 It's like saying you can taste green - it doesn't make sense.这就像说你可以尝到绿色——这是没有意义的。

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

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