1. 其它 请编写一个Person类,至少包含三个属性,两个方法,并创建一个Person的对象(对象名为你姓名的拼音),完成对属性赋值和方法调用。 定义一个学生类继承Person类,测试子类继承父类中哪些属性和方法,当子类重写父类中某个方法时,如何让其调用父类中的方法。
时间: 2023-05-26 08:04:02 浏览: 103
设计一个Person类,有Person类派生一个Student类和一个Teacher类
Person类:
```java
public class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public void introduce() {
System.out.println("My name is " + this.name + ", I am " + this.age + " years old, and I am " + this.gender + ".");
}
public void sayHello() {
System.out.println("Hello, my name is " + this.name + ".");
}
}
```
创建对象:
```java
Person huangxing = new Person("Huang Xing", 28, "male");
huangxing.introduce();
huangxing.sayHello();
```
输出:
```
My name is Huang Xing, I am 28 years old, and I am male.
Hello, my name is Huang Xing.
```
学生类:
```java
public class Student extends Person {
private int grade;
private String major;
public Student(String name, int age, String gender, int grade, String major) {
super(name, age, gender);
this.grade = grade;
this.major = major;
}
@Override
public void introduce() {
super.introduce();
System.out.println("I am a student in grade " + this.grade + ", majoring in " + this.major + ".");
}
public void study() {
System.out.println("I am studying...");
}
}
```
测试:
```java
Student huangxing = new Student("Huang Xing", 28, "male", 5, "Computer Science");
huangxing.introduce();
huangxing.sayHello();
huangxing.study();
```
输出:
```
My name is Huang Xing, I am 28 years old, and I am male.
I am a student in grade 5, majoring in Computer Science.
Hello, my name is Huang Xing.
I am studying...
```
子类继承了父类中的属性和方法,可以直接使用。子类可以重写父类中的方法,使用`@Override`注解进行标识。如果子类想要调用父类中的方法,可以使用`super`关键字。例如,在`Student`类中重写了`introduce()`方法,但是又想要调用父类中的`introduce()`方法,可以这样写:
```java
@Override
public void introduce() {
super.introduce();
System.out.println("I am a student in grade " + this.grade + ", majoring in " + this.major + ".");
}
```
阅读全文