java - 在继承类的 super 方法中返回 `this`

标签 java inheritance polymorphism this

假设我有类 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));
}

我的问题出在 a2a3 对象上, a3 基本上就是 a2.get2(),按照该方法执行后会到达 A get1() 方法返回 this

由于该方法是在类 A 中找到的,我确信它只会返回对对象 a2A 部分的引用,而不是对整个对象的引用,

所以当我尝试这条线时: a3.getClass() == A.class 我会得到True

当我调试时a3.getClass()是“B类”。

有人可以向我解释一下 return this 行在父类中实际执行的操作吗?

谢谢!

最佳答案

让我们一步步追踪这些语句:

  1. a1 是对 A 类型实例的引用。
  2. a1.get2() 调用 A 中的 get2() 方法,该方法返回对 B 类型实例的引用 所以a2 指的是B 类型的实例。
  3. a2.get2() 调用 B 中的 get2() 方法。请记住,a2B 类型的实例,因此 this 引用 B
  4. B 中的
  5. get2() 方法调用B 中的get1() 方法。 this 仍然引用 B
  6. B 中的
  7. get1() 方法调用 super.get1()。这就是可能会让人有点困惑的地方。即使您从父类调用 get1 方法,this 在运行时仍然引用 B
  8. 因此,super.get1() 返回 BB 中的 get1() 返回 BB 中的 get2() 返回 B。因此,a3 引用 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/

相关文章:

c# - Fluent API EF 继承和映射

c - C 中的面向对象程序 - 列表

c# - foreach(新列表<Base>()中的派生对象)

java - 在 Java 中,如何从派生类中的覆盖方法调用基类的方法?

java - 在 JFrame 中键入会出现错误

java - 在服务器端使用 Java Swing 结合 php 上传文件

java - 如何从 NetBeans 6.8 中的其他项目导入 java 类?

c++ - VS2013中继承构造函数

Java泛型继承神秘错误

java - 设计拼图