gpt4 book ai didi

java - 继承3个类

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:54:56 27 4
gpt4 key购买 nike

代码:

    class Super {
void print(Super a) {
System.out.print("Super");
}
}
class Base extends Super{
void print(Base a) {
System.out.print("Base");
}
}
class Derived extends Base{
void print(Derived a) {
System.out.print("Derived");
}
}
class Test {
public static void main(String args[]){
Super a1= new Super();
Super b1= new Base();
Base c1= new Derived();
a1.print(new Base());
b1.print(new Derived());
c1.print(new Derived());
}
}

输出:“SuperSuperBase”

它是如何工作的,请解释一下?我知道不可能给出简短的答案,但是..很难理解

最佳答案

output: "SuperSuperBase"

    Super a1= new Super();
a1.print(new Base());

Super 类对象是通过 Super 创建的。 Super 类的 print() 方法将被调用。

    Super b1= new Base();
b1.print(new Derived());

这里的b1 是类型Super 类的引用。所以 Super 类的 print() 方法将被调用。

    Base c1= new Derived();      
c1.print(new Derived());

这里的c1 是类型Base 类的引用。所以 Base 类的 print() 方法将被调用。

关于java - 继承3个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35414548/

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