1. this 关键字
this 表示 当前对象的引用,可以用来访问对象的属性、方法,或者调用同类的构造方法。
1.1 访问当前对象的属性
当局部变量和成员变量重名时,用 this 区分:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name; // this.name 指成员变量
this.age = age; // age 是局部变量
}
public void sayHello() {
System.out.println("我叫" + this.name + ",今年" + this.age + "岁");
}
}
1.2 调用当前对象的方法
public class Person {
public void eat() {
System.out.println("吃饭");
}
public void live() {
this.eat(); // 调用当前对象的 eat 方法
System.out.println("生活");
}
}
1.3 调用同类的构造方法(构造器重载)
public class Person {
private String name;
private int age;
public Person() {
this("未知", 0); // 调用带参构造方法
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
✅ 总结 this 用途:
-
引用当前对象属性或方法
-
调用同类其他构造方法
-
在方法链或构造方法中增强可读性
2. super 关键字
super 表示 父类对象的引用,用于访问父类的属性、方法或构造方法。
2.1 访问父类属性
class Animal {
String name = "动物";
}
class Dog extends Animal {
String name = "狗";
public void printNames() {
System.out.println(name); // 子类属性
System.out.println(super.name); // 父类属性
}
}
2.2 调用父类方法
class Animal {
public void eat() {
System.out.println("动物吃东西");
}
}
class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃骨头");
}
public void test() {
eat(); // 调用子类重写方法
super.eat(); // 调用父类方法
}
}
2.3 调用父类构造方法
class Animal {
String name;
public Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
public Dog(String name) {
super(name); // 调用父类构造方法初始化 name
}
}
✅ 总结 super 用途:
-
访问父类属性(被子类覆盖时使用)
-
调用父类方法(被子类重写时使用)
-
调用父类构造方法(必须是子类构造方法第一行)
3. this 与 super 区别对比
| 关键字 | 指向对象 | 用途 |
|---|---|---|
this | 当前对象 | 访问本类属性、方法,调用本类构造方法 |
super | 父类对象 | 访问父类属性、方法,调用父类构造方法 |
4. 小结与示例
class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " 在吃");
}
}
class Dog extends Animal {
String name = "狗";
public Dog(String name) {
super(name); // 调用父类构造方法
}
public void show() {
System.out.println(this.name); // 子类属性
System.out.println(super.name); // 父类属性
this.eat(); // 子类方法(如果重写了)
super.eat(); // 父类方法
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("旺财");
dog.show();
}
}
✅ 输出:
狗
旺财
旺财 在吃
旺财 在吃
1068



被折叠的 条评论
为什么被折叠?



