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?
}
}发布于 2013-03-24 15:37:13
简单的解释:当你使用
SuperClass obj = new SubClass();只有在SuperClass中定义的公共方法是可访问的。在SubClass中定义的方法则不是。
当您使用
SubClass obj = new SubClass(); 在SubClass中定义的公共方法也可以与SuperClass公共方法一起访问。
在两种情况下创建的对象是相同的。
例如:
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.发布于 2013-03-24 15:36:15
使用上面的代码创建的两个对象有什么不同?
这两个对象完全相同。不同的是存储对象引用的变量的类型。在实践中,这意味着如果有任何特定于subClass的方法,您将能够通过sc2访问它们,但不能通过sc1访问它们(后者需要强制转换)。
发布于 2013-03-24 15:38:48
在这两种情况下,都会创建subClass的对象,但引用会有所不同。
使用superClass的引用,即sc1,您将无法调用subClass中的方法,但不能调用superClass中的方法。您将需要强制转换来调用subClass方法。
像这样:
class superClass {
public void superClassMethod(){
}
}
class subClass extends superClass{
public void subClassMethod(){
}
}现在:
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?
sc2.subClassMethod(); //this is valid
sc1.subClassMethod(); // this is a compiler error,
// as no method named subClassMethod
// is present in the superClass as the
// reference is of superClass type
// for this you require a type cast
(subClass)sc1.subClassMethod(); // Now this is valid
}
}https://stackoverflow.com/questions/15596193
复制相似问题