如果我用Superclass来初始化一个子类对象,为什么这个对象有子类的属性却有父类的方法呢?
If I use Superclass to initialize a subclass object, why will the object have the attributes of the subclass and but the methods of the superclass?
我想明白为什么会这样,优点如下现象有什么用:我用Superclass初始化了一个子类对象,为什么这个对象会有子类的属性却没有方法超类的?
查看代码以了解我的真正意思:
class SuperClass {
public String s = "'This is the superclass'";
public String method() {
return s;
}
}
class SubClass extends SuperClass {
public String s = "'This is the subclass'";
public String method() {
return s;
}
}
public class SubClassTest {
public static void main(String[] args) {
SuperClass sc = new SuperClass();
System.out.println("Superclass s: " + sc.s + " bzw. method: " + sc.method());
SubClass subc = new SubClass();
System.out.println("SubClass s: " + subc.s + " bzw. method: " + subc.method());
SuperClass x = subc;
System.out.println("x s: " + x.s + " bzw. method: " + x.method());
}
}
输出如下:
Superclass s: 'This is the superclass' bzw. method: 'This is the superclass'
SubClass s: 'This is the subclass' bzw. method: 'This is the subclass'
x s: 'This is the superclass' bzw. method: 'This is the subclass'
正如 Ramkumar 所说 link 可能对您有所帮助
您不能覆盖已经定义的 class 的结构,您可以覆盖其行为。 class 的变量本质上不是多态的。
我想明白为什么会这样,优点如下现象有什么用:我用Superclass初始化了一个子类对象,为什么这个对象会有子类的属性却没有方法超类的?
查看代码以了解我的真正意思:
class SuperClass {
public String s = "'This is the superclass'";
public String method() {
return s;
}
}
class SubClass extends SuperClass {
public String s = "'This is the subclass'";
public String method() {
return s;
}
}
public class SubClassTest {
public static void main(String[] args) {
SuperClass sc = new SuperClass();
System.out.println("Superclass s: " + sc.s + " bzw. method: " + sc.method());
SubClass subc = new SubClass();
System.out.println("SubClass s: " + subc.s + " bzw. method: " + subc.method());
SuperClass x = subc;
System.out.println("x s: " + x.s + " bzw. method: " + x.method());
}
}
输出如下:
Superclass s: 'This is the superclass' bzw. method: 'This is the superclass'
SubClass s: 'This is the subclass' bzw. method: 'This is the subclass'
x s: 'This is the superclass' bzw. method: 'This is the subclass'
正如 Ramkumar 所说 link 可能对您有所帮助
您不能覆盖已经定义的 class 的结构,您可以覆盖其行为。 class 的变量本质上不是多态的。