class Super {
public Integer i = 1;
void Sample() {
System.out.println("method of super class");
}
}
public class Sub extends Super {
public Integer i = 1000;
void Sample() {
System.out.println("method of sub class");
}
public static void main(String args[]) {
Super obj;
obj = new Super();
obj.Sample();
System.out.println(obj.i);
obj = new Sub();
obj.Sample();
System.out.println(obj.i);
}
}
输出:
method of super class
1
method of sub class
1
调用Sample()方法时,因此得到不同的输出(超类/子类的方法)
但是当我打印i变量时,输出是相同的(1)
引用/对象类型或继承规则是否存在问题?
感谢提前答复
答案 0 :(得分:0)
Java中的变量不遵循多态性,并且重写仅适用于方法,而不适用于变量。因此,您会看到方法Sample()
的替代行为,但没有看到变量i
的替代行为。
请注意,在这种情况下,子类变量隐藏了父类变量,其概念称为variable hiding。