this 和 super 的区别解析

在Java中,thissuper 是两个关键字,用于在类的成员方法或构造方法中引用当前对象或父类对象。它们的核心区别如下:

图片[1]_this 和 super 的区别解析_知途无界

1. 核心区别

关键字指向对象主要用途
this当前类的实例访问当前类的成员(属性和方法)、解决局部变量与成员变量同名问题、调用当前类的其他构造方法。
super直接父类的实例访问父类的成员(属性和方法)、调用父类的构造方法(必须在子类构造方法的第一行)。

2. 具体用法对比

(1) 访问成员变量

class Parent {
    String name = "Parent";
}

class Child extends Parent {
    String name = "Child";

    void printNames() {
        System.out.println(super.name); // 输出: Parent(父类的name)
        System.out.println(this.name);   // 输出: Child(当前类的name)
    }
}

(2) 调用成员方法

class Parent {
    void show() {
        System.out.println("Parent's method");
    }
}

class Child extends Parent {
    void show() {
        super.show(); // 调用父类的show()
        System.out.println("Child's method");
    }
}

(3) 调用构造方法

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

class Child extends Parent {
    Child() {
        super(); // 隐式调用父类无参构造(可省略)
        System.out.println("Child Constructor");
    }
}

3. 关键注意事项

  1. super 必须显式调用父类有参构造
    如果父类没有无参构造,子类必须通过 super(args) 显式调用父类的有参构造,否则编译报错。
  2. this()super() 不能共存
    在构造方法中,this()(调用当前类其他构造方法)和 super() 必须二选一,且必须在第一行。
  3. 静态上下文中无效
    thissuper 不能在静态方法(static)中使用,因为它们是实例相关的。

4. 面试常见问题

Q1: 能否用 this 调用父类方法?

:不能。this 始终指向当前类实例,若子类重写了父类方法,this.method() 调用的是子类的方法。

Q2: 什么情况下必须用 super

  • 父类和子类有同名成员变量/方法时,需用 super 明确指定父类成员。
  • 子类构造方法中需调用父类有参构造时。

Q3: 以下代码输出什么?

class A {
    A() {
        System.out.println("A");
    }
}

class B extends A {
    B() {
        System.out.println("B");
    }
}

new B();

A  // 先隐式调用父类无参构造
B

总结

  • this:立足当前类,解决成员与局部变量冲突或链式调用构造方法。
  • super:穿透到父类,突破子类重写或调用父类构造方法。
  • 两者均体现面向对象中封装和继承的核心思想。
© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞84 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容