gpt4 book ai didi

Java继承基类使用派生类方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:48:36 26 4
gpt4 key购买 nike

最近我偶然发现了 Java 测试并发现了一个奇怪的行为。

class MainOne {

private int i = 5;

public MainOne() {
System.out.println("MainOne says that I is " + getI());
}

public int getI() {
System.out.println("MainOne getI was used");
return i;
}

}

public class TheTest extends MainOne {

private static int i = 10;

public TheTest() {
System.out.println("TheTest says that I is " + super.getI());
}


public int getI() {
System.out.println("TheTest getI was used");
return i;
}

public static void main(String[] args) {
TheTest test = new TheTest();
}

}

结果是:

TheTest getI was used

MainOne says that I is 10.

MainOne getI was used

TheTest says that I is 5

问题是,发生了什么?基类怎么用它的后代方法?

最佳答案

这都是关于执行顺序和构造函数继承的。 TheTest 构造函数隐式调用 super MainOne 构造函数。

所以

public TheTest() {
System.out.println("TheTest says that I is " + super.getI());
}

通话

public MainOne() {
System.out.println("MainOne says that I is " + getI());
}

由于多态性,它调用覆盖的 getI()

public int getI() {
System.out.println("TheTest getI was used");
return i;
}

这里的i就是TheTest中声明的static i。最后

super.getI());

被调用,它使用 MainOnei

你因此得到

TheTest getI was used

MainOne says that I is 10.

MainOne getI was used

TheTest says that I is 5

请注意,多态性不适用于字段,并且字段(无论是 static 还是 instance)可能会隐藏父类中的同名字段。

关于Java继承基类使用派生类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19746547/

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