this 和 super 关键字有什么作用,请写程序说明?
时间: 2024-02-29 10:53:16 浏览: 18
this 和 super 都是 Java 中的关键字,它们分别表示当前对象和父类对象的引用。
this 关键字的作用是指代当前对象,可以用来区分同名的实例变量和局部变量。例如:
```
public class Person {
private String name;
public void setName(String name) {
this.name = name; // 使用 this 关键字指代实例变量 name
}
}
```
super 关键字的作用是指代父类对象,可以用来调用父类的构造方法或者父类的成员变量和成员方法。例如:
```
public class Student extends Person {
private String school;
public Student(String name, String school) {
super(name); // 调用父类的构造方法
this.school = school;
}
public void printInfo() {
System.out.println("Name: " + super.getName()); // 调用父类的方法
System.out.println("School: " + this.school);
}
}
```
在这个例子中,super.getName() 调用了父类 Person 的 getName() 方法。