java在原来写的student类、teacher类和people类的基础上,将父类people类中的部分方法重写,部分成员变量隐藏。
时间: 2023-06-27 08:04:09 浏览: 115
好的,你可以先在people类中定义需要被重写的方法,并将需要隐藏的成员变量定义为private。接下来,在子类中使用@Override注解重写父类中的方法,并使用super关键字来调用父类中被重写的方法。同时,在子类中新增自己的成员变量和方法以满足特定需求。以下是示例代码:
```java
public class People {
private String name;
private int age;
public People(String name, int age) {
this.name = name;
this.age = age;
}
public void introduce() {
System.out.println("My name is " + name + ", and I am " + age + " years old.");
}
public void work() {
System.out.println("I am working.");
}
}
public class Student extends People {
private String school;
public Student(String name, int age, String school) {
super(name, age);
this.school = school;
}
@Override
public void introduce() {
System.out.println("I am a student. My name is " + getName() + ", and I am " + getAge() + " years old. I study at " + school + ".");
}
public void study() {
System.out.println("I am studying.");
}
}
public class Teacher extends People {
private String subject;
public Teacher(String name, int age, String subject) {
super(name, age);
this.subject = subject;
}
@Override
public void introduce() {
System.out.println("I am a teacher. My name is " + getName() + ", and I am " + getAge() + " years old. I teach " + subject + ".");
}
public void teach() {
System.out.println("I am teaching.");
}
}
```
在子类中重写父类中的方法时,需要注意以下几点:
1. 访问修饰符不能比父类中的更严格;
2. 返回类型必须与父类中的相同或是其子类;
3. 方法名和参数列表必须与父类中的相同。
阅读全文