17370845950

在Java中this和super能同时使用吗
构造方法中只能选择调用本类或其他构造方法之一作为首行语句,因此this()和super()不能同时直接使用,但可在不同构造方法中分别调用,实现间接共存,而在成员访问时二者可自由并存。

在Java中,thissuper不能在同一个构造方法调用中同时作为第一条语句使用。

为什么不能同时使用?

因为在Java构造方法中,调用其他构造方法(无论是本类的还是父类的)都必须放在第一行。这意味着你只能选择调用本类的另一个构造方法(使用 this()),或者调用父类的构造方法(使用 super()),二者只能选其一。

例如,下面的代码是非法的:

this();
super(); // 编译错误:super() 必须在第一行,且不能和 this() 同时出现

可以间接共存

虽然不能在同一个构造方法中直接同时调用 this()super(),但它们可以在不同的构造方法中分别被使用,从而在整个构造链中“共存”。

比如:

class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        this("default");
    }

    Child(String name) {
        super(); // 调用父类构造方法
        System.out.println("Child constructor with name: " + name);
    }
}

在这个例子中:

  • Child() 使用 this("default") 调用本类的另一个构造方法
  • Child(String name) 使用 super() 调用父类构造方法
  • 整个构造流程合法,thissuper 在不同构造方法中被使用

成员访问时可以同时出现

在普通方法或构造方法中,你可以同时使用 thissuper 来访问成员变量或方法,这没有限制。

例如:

void display() {
    System.out.println(this.value);     // 访问本类的属性
    System.out.println(super.value);    // 访问父类的属性
    this.method();                      // 调用本类方法
    super.method();                     // 调用父类方法
}

这种用法完全合法,因为不涉及构造方法调用顺序的问题。

基本上就这些。构造方法中只能选一个作为首行调用,但成员访问时可以自由使用两者。