在 Java 中,“this”在继承该方法的子类上调用的超类方法中表示什么?

Mer*_*ack 6 java subclass this superclass

代码是这样的:

class Main {  
  public static void main(String args[]) { 
        Person p1 = new Student();
        Person p3 = new Teacher();
        Student p4 = new Student();
        OnlineLecture lec3 = new OnlineLecture();
        
        lec3.addAttendant(p1);
        lec3.addAttendant(p3);
        lec3.addAttendant(p4);
  }
}


abstract class Person {
    public void join(Lecture lec) { 
        System.out.println("Joining "+lec);
    }
    public void join(OnlineLecture lec) {
        System.out.println("Joining "+lec);
    }
}

class Student extends Person {
    public void join(Lecture lec) {
        System.out.println("Student joining "+lec);
    }
}

class Teacher extends Person {
    public void join(OnlineLecture lec) {
        System.out.println("Teacher joining "+lec);
    }
}
    
class Lecture {
    public void addAttendant(Person p) {
        p.join(this);
    }
    public String toString() {
        return "a lecture";
    }
}

class OnlineLecture extends Lecture {
    public String toString() {
        return "an online lecture";
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我得到的输出是这样的:

Student joining an online lecture
Joining an online lecture
Student joining an online lecture
Run Code Online (Sandbox Code Playgroud)

不应该在 lec3 上调用的“addAttendant”方法中的“join(this)”导致“join(OnlineLecture lec3)”,因此给出这个

Joining an online lecture
Teacher joining an online lecture
Joining an online lecture
Run Code Online (Sandbox Code Playgroud)

作为输出?

Thi*_*esh 4

多态性和重载

多态性

  1. reference.method()当调用a 时就会表现出多态性
  2. 这本质上是一种基于实际object类型引用的动态行为reference
  3. 这就是查找表(如 C++ 中的 vmt)发挥作用的地方
  4. 根据引用指向的对象,运行时将决定要调用的实际方法

超载

  1. 编译时决策中的方法重载
  2. 方法的签名在编译时就固定了
  3. 基于方法的参数类型展示的任何多态性都不需要运行时查找
  4. 该参数只是上下文中方法的参数,它不关心类型所表现出的多态性

当前示例中发生了什么?

    static class Lecture {
        public void addAttendant(Person p) {
            p.join(this);
        }
    }
Run Code Online (Sandbox Code Playgroud)
  1. 假设有一个 Lecture 的子类重写,那么当有人调用其引用类型或其之一的方法时addAttendant,多态性可以根据类型控制调用哪个方法。objectLecturesubclass(es)
  2. 但是,对于最终落在 上的任何调用,与isLecture.addAttendant匹配的方法签名(即使可以动态引用)。即使所引用的对象可能是多态类型,这里也不存在多态性。p.join(this)join(Lecture)pthis

  • 将“this”解析为参数完全依赖于方法的参考框架,在这种情况下,运行时解析的方法位于“Lecture”类内部,因此它与“p”(或任何它的子类 - 多态性用于“p”),与带有“Lecture”签名的方法相匹配。 (2认同)