Returning `this` in a super method of inherited class
假设我有类
答:
1 2 3 4 5 6 7 8 9 10 11 12 | public class A { public int x; public static int y; public A(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public static int getY() { return y; } public A get1() { return this; } public A get2() { return new B(x, y); } } |
B:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class B extends A { public int x; public B(int x, int y) { super(x, y); this.x = x*2; this.y = y*2; } public int getX() { return x; } public static int getY() { return y*3; } public A get1() { x++; return super.get1(); } public A get2() { return get1(); } } |
号
主要功能如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static void main(String[] args) { A a1 = new A(5, 10); A a2 = a1.get2(); A a3 = a2.get2(); System.out.println("a1.x=" + a1.x); System.out.println("a1.y=" + a1.y); System.out.println("a2.x=" + a2.x); System.out.println("a2.getX()=" + a2.getX()); System.out.println("a2.getY()=" + a2.getY()); System.out.println("((B)a2).getY()=" + ((B)a2).getY()); System.out.println("((B)a2).x=" + ((B)a2).x); System.out.println("a3 is A:" + (a3.getClass() == A.class)); System.out.println("a3 is B:" + (a3 instanceof B)); System.out.println("a3==a2:" + (a3 == a2)); } |
我的问题是
由于该方法是在类
所以当我尝试这一行时:a3.getClass()==A.Class我去叫
当我调试
有人能给我解释一下,当
谢谢!
让我们一步一步地跟踪语句:
从Java文档的EDOCX1到37
public final Class getClass()
Returns the runtime class of this Object
号
关键字
所以你有一个b对象,在a中声明的方法中有一个