this指向当前对象实例,用于区分成员与局部变量、调用本类构造器或返回当前对象;super指向父类实例,用于调用父类构造器、访问被隐藏的成员或执行被重写的方法。两者在继承中作用不同,使用时需注意调用顺序和访问权限。

this 和 super 是 Java 中两个重要的关键字,它们都用于引用对象实例,但作用对象和使用场景不同。理解它们的区别对掌握 Java 面向对象编程非常关键。
this 代表当前类的实例对象,也就是正在调用方法或构造器的那个对象。它主要用于以下几种情况:
public class Person {
private String name;
public Person(String name) {
this.name = name; // this.name 表示成员变量,name 是参数
}
public Person setName(String name) {
this.name = name;
return this; // 返回当前对象,支持链式调用
}
}super 用于访问父类(直接超类)的成员,包括变量、方法和构造器。它在继承关系中特别重要。
class Animal {
protected String type = "animal";
public Animal() {
System.out.println("Animal constructor");
}
public void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
private String type = "dog";
public Dog() {
super(); // 调用父类构造器
}
public void printType() {
System.out.println(this.type); // 输出 dog
System.out.println(super.type); // 输出 animal
}
@Override
public void sound() {
super.sound(); // 先执行父类方法
System.out.println("Bark!");
}
}以上就是在Java中this与super关键字的区别是什么的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号