本文介绍了什么是subClass sc = new subClass()和superClass sc = new subClass之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
}
}
推荐答案
简单说明:
当你使用
Simple explanation :When you use
SuperClass obj = new SubClass();
只有在 SuperClass
中定义的公共方法可以访问。 SubClass
中定义的方法不是。
Only public methods that are defined in SuperClass
are accessible. Methods defined in SubClass
are not.
当您使用
SubClass obj = new SubClass();
SubClass
中定义的公共方法也可访问以及 SuperClass
公共方法。
public methods defined in SubClass
are also accessible along with the SuperClass
pubic methods.
在两种情况下创建的对象都是相同的。
Object created in both cases is the same.
Ex:
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.
这篇关于什么是subClass sc = new subClass()和superClass sc = new subClass之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!