gpt4 book ai didi

java - java 中得到意外的输出

转载 作者:行者123 更新时间:2023-12-01 07:07:02 24 4
gpt4 key购买 nike

我有一些java代码:

class Protected{
int n = 1;

public Protected(){
System.out.println("Constructor of protected");
System.out.println("========================");
System.out.println("n = "+n);
System.out.println();
}
}
class Derived extends Protected{
Derived(){
System.out.println("Constructor of derived");
System.out.println("======================");
System.out.println("n = "+(n+1));
}
}

public class Demo{
public static void main(String args[]){
Derived ob2 = new Derived();
}
}

我得到的输出为:

constructor of protected
========================
n=1

constructor of Derived
========================
n=2

这就是我想要的:

constructor of Derived
========================
n=2

最佳答案

必须为子类的每个新实例调用父类(super class)构造函数。如果您没有在子类构造函数中提供对父类(super class)构造函数的显式调用,那么 Java 将插入对无参数父类(super class)构造函数的隐式调用。这解释了为什么您会看到父类(super class)构造函数的输出。

要删除该输出,您可以执行以下操作之一:

1) 从父类(super class)构造函数中删除输出语句。

2)在父类(super class)中创建另一个不输出任何内容的构造函数,并在子类构造函数中显式调用它。

Section 8.8.7 of the JLS状态:

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

关于java - java 中得到意外的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21734841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com