class A { public static void main(String[] args)
{ A a = new A();
B b = new B();
A ab = new B();
System.out.format("%d %d %d %d %d %d", a.x, b.x, ab.x, a.y, b.y, ab.y); }
int x = 2;
int y = 3;
A(int x) { this.x = x; }
A() { this(7); } }
class B extends A {
int y = 4;
B() { super(6);
}大家好,我只是在浏览我的课程中的一些例子,遇到了这个难住我的问题。
我意识到这段代码应该打印出"7 6 6 3 4 3“
但是为什么ab.y等于3呢?"real“类型的对象不是B类的ab吗?这会让我相信ab.y是4吗?
发布于 2010-09-28 09:56:26
因为您直接访问字段,而不是通过getter方法。
您不能重写字段,只能重写方法。
除了父类A中的字段外,类B还有一个字段y。这两个字段不会相互干扰,哪个字段会在编译时确定(由编译器已知的类型决定)。
如果你说
A ab = new B(); 然后
ab.y将被编译以查看在类A中声明的字段y。这不会在运行时被分派到实际实例的类。静态方法也是如此。
如果你这样做了
B ab = new B();然后在B类中获取该字段。
https://stackoverflow.com/questions/3809139
复制相似问题