假设我有类 A
和类 B
,它们扩展了 A
,
以下是类(class):
答:
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:
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(); }
}
主要功能如下:
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));
}
我的问题出在 a2
和 a3
对象上,
a3
基本上就是 a2.get2()
,按照该方法执行后会到达 A
get1()
方法返回 this
。
由于该方法是在类 A
中找到的,我确信它只会返回对对象 a2
的 A
部分的引用,而不是对整个对象的引用,
所以当我尝试这条线时:
a3.getClass() == A.class
我会得到True
。
当我调试时a3.getClass()
是“B类”。
有人可以向我解释一下 return this
行在父类中实际执行的操作吗?
谢谢!
最佳答案
让我们一步步追踪这些语句:
a1
是对A
类型实例的引用。a1.get2()
调用A
中的get2()
方法,该方法返回对B 类型实例的引用
所以a2
指的是B
类型的实例。a2.get2()
调用B
中的get2()
方法。请记住,a2
是B
类型的实例,因此this
引用B
。get2()
方法调用B
中的get1()
方法。this
仍然引用B
。get1()
方法调用super.get1()
。这就是可能会让人有点困惑的地方。即使您从父类调用get1
方法,this
在运行时仍然引用B
。- 因此,
super.get1()
返回B
。B
中的get1()
返回B
。B
中的get2()
返回B
。因此,a3
引用B
类型的实例。
B
中的B
中的 来自Object#getClass
的java文档
public final Class getClass()
Returns the runtime class of this Object
getClass
方法返回对象的运行时类,这就是当您对 B< 类型的实例的引用调用
。如果 getClass
时得到的结果getClass
未设计为返回实际实例类型,则它始终返回 Object
,这将使该方法毫无意义。
关于java - 在继承类的 super 方法中返回 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30954806/