开发者

Real vs Apparent classes in Java

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); 
  }

Hey all, I was just looking through some examples from my course and came across this problem that stumped me.

I realize that that this code should print out "7 6 6 3 4 3"

But why is ab.y equal to 3? Isn't the "real" type of object ab of class B? Which then would lead me to believe that ab.y be 4?


Because you are accessing the fields directly, and not via getter methods.

You cannot override fields, only methods.

Class B has a field y in addition to the one in parent class A. The two fields do not interfere with each-other, which one gets picked up is determined at compile-time (by the type known to the compiler).

If you say

   A ab = new B(); 

then

  ab.y

will be compiled to look at the field y declared in class A. This is not dispatched at runtime to the real instance's class. It would be the same with a static method.

If you do

    B ab = new B();

then you get the field in class B.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜