gpt4 book ai didi

java - "ParentClass objectName1= new SubClass() "和 "SubClass objectName2 = new SubClass()"有什么区别?

转载 作者:行者123 更新时间:2023-12-02 08:33:37 27 4
gpt4 key购买 nike

我想知道在从另一个扩展的类中创建对象的这两种方法之间是否存在任何功能差异。

我只是在处理基本的继承,除了 Cat extends Mammal 之类的东西之外没有什么复杂的。

最佳答案

ParentClass objectName = new SubClass() - 父类引用持有子类对象

class ParentClass{
void m1(){
System.out.println("parent m1");
}
void m2(){
System.out.println("parent m2");
}
}

class SubClass extends ParentClass{
//subclass overriding parent class m1 method
@Override
void m1(){
System.out.println("child m1");
}
void m3(){
System.out.println("child m3");
}
}

class Test{
public static void main(String[] args){
ParentClass p = new SubClass();
p.m1();// out puts child m1 as child class is overriding m1 method
p.m2();//out puts parent m2 as child class is not overriding m2 method
p.m3();//gives compile time error as parent class reference doesn't know about m3 method

}
}

关于java - "ParentClass objectName1= new SubClass() "和 "SubClass objectName2 = new SubClass()"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24218852/

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