编写一个使用this和super关键字的程序
时间: 2023-06-04 14:06:30 浏览: 89
如何编这样的程序
好的,这是一个关于使用this和super关键字的示例代码:
```java
public class Person {
private String name;
private int age;
public Person() {
this.name = "Unknown";
this.age = 0;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
}
public class Student extends Person {
private int studentId;
public Student() {
super();
this.studentId = 0;
}
public Student(String name, int age, int studentId) {
super(name, age);
this.studentId = studentId;
}
public void display() {
super.display();
System.out.println("Student ID: " + this.studentId);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Tom", 20, 12345);
s1.display();
s2.display();
}
}
```
这段代码定义了两个类:`Person`和`Student`。`Person`类具有`name`和`age`属性和一个构造函数,`Student`类继承自`Person`类并添加了`studentId`属性。`Student`类也有一个构造函数和`display`方法,该方法调用`super.display()`来显示Person类的属性并添加studentId。在`main`函数中,我们创建了两个`Student`类的实例并调用它们的`display`方法。`this`关键字用于引用当前类的属性,`super`关键字用于引用父类的属性或方法。
阅读全文