this和super什么含义?如何使用?(解释并写出相关代码)
时间: 2024-03-25 11:38:31 浏览: 12
`this`和`super`都是关键字,用于在Java中引用类的成员和方法。
`this`关键字用于引用当前对象的成员和方法。它有以下几种用途:
1. 引用当前对象的成员变量:
```java
public class Person {
private String name;
public Person(String name) {
this.name = name; // 使用this关键字引用成员变量
}
}
```
2. 引用当前对象的方法:
```java
public class Person {
private String name;
public Person(String name) {
this.setName(name); // 使用this关键字引用方法
}
public void setName(String name) {
this.name = name;
}
}
```
3. 在构造函数中调用另一个构造函数:
```java
public class Person {
private String name;
private int age;
public Person(String name) {
this(name, 0); // 调用另一个构造函数
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
```
`super`关键字用于引用父类的成员和方法。它有以下几种用途:
1. 引用父类的构造函数:
```java
public class Student extends Person {
private String school;
public Student(String name, int age, String school) {
super(name, age); // 调用父类构造函数
this.school = school;
}
}
```
2. 引用父类的成员变量和方法:
```java
public class Student extends Person {
private String school;
public Student(String name, int age, String school) {
super(name, age);
this.school = school;
}
public void printInfo() {
System.out.println(super.getName()); // 引用父类的成员变量
super.printInfo(); // 引用父类的方法
}
}
```
以上是`this`和`super`关键字的一些基本用法,可以根据具体情况进行灵活运用。