gpt4 book ai didi

java - subClass sc = new subClass() 和 superClass sc = new subClass 有什么区别?

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

class superClass {}

class subClass extends superClass{}

public class test
{

public static void main()

{

superClass sc1 = new subClass();
subClass sc2 = new subClass();
//whats the difference between the two objects created using the above code?

}
}

最佳答案

简单解释:当您使用时

SuperClass obj = new SubClass();

只有在SuperClass中定义的公共(public)方法才可以访问。 SubClass 中定义的方法不是。

当您使用时

SubClass obj = new SubClass(); 

SubClass中定义的公共(public)方法也可以与SuperClass公共(public)方法一起访问。

两种情况下创建的对象是相同的。

例如:

public class SuperClass {

public void method1(){

}
}

public class SubClass extends SuperClass {
public void method2()
{

}
}

SubClass sub = new SubClass();
sub.method1(); //Valid through inheritance from SuperClass
sub.method2(); // Valid

SuperClass superClass = new SubClass();
superClass.method1();
superClass.method2(); // Compilation Error since Reference is of SuperClass so only SuperClass methods are accessible.

关于java - subClass sc = new subClass() 和 superClass sc = new subClass 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596193/

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