Java.定义 Person 类与其子类 Student 类,在程序中使用 super、super()、this、superl),内容自拟。
时间: 2024-03-01 09:51:34 浏览: 24
好的,我来为您解答这个问题。
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void eat() {
System.out.println("Person is eating.");
}
}
public class Student extends Person {
private int grade;
public Student(String name, int age, int grade) {
super(name, age);
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void study() {
System.out.println("Student is studying.");
}
@Override
public void eat() {
super.eat();
System.out.println("Student is also eating.");
}
}
```
在上面的代码中,我们定义了一个 Person 类和一个它的子类 Student 类。
在 Student 类中,我们使用了 super() 来调用父类的构造方法来初始化 Person 类中的属性 name 和 age,因为子类中没有这两个属性,需要借助父类的构造方法来进行初始化。
在 eat() 方法中,我们使用了 super.eat() 来调用父类的 eat() 方法,然后再在子类中添加一些额外的行为。
在子类中也可以使用 this 来调用自己的属性和方法,使用 super 来调用父类的属性和方法。例如:
```java
public class Student extends Person {
private int grade;
public Student(String name, int age, int grade) {
super(name, age);
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void study() {
this.eat();
super.eat();
System.out.println("Student is studying.");
}
@Override
public void eat() {
super.eat();
System.out.println("Student is also eating.");
}
}
```
在上面的代码中,我们在 study() 方法中使用了 this.eat() 来调用子类的 eat() 方法,使用 super.eat() 来调用父类的 eat() 方法。这样可以方便地调用不同类的方法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)