代码示例
public class OverrideExercise {
public static void main(String[] args) {
Person jack = new Person("jack", 18);
System.out.println(jack.say());
Student smith = new Student("smith", 18, 1, 99);
System.out.println(smith.say());
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String say() {
return "name=" + name + ",age=" + age;
}
}
class Student extends Person {
private int id;
private double score;
public Student(String name, int age, int id, double score) {
super(name, age);
this.id = id;
this.score = score;
}
@Override
public String say() {
return super.say() + ",id=" + id + ",score=" + score;
}
}
注意事项
- 方法重写override存在于父类与子类中
- 方法名保持一致
- 方法形参列表保持一致
- 子类方法的返回值应与父类方法返回值一致或者为其子类
- 父类返回值若为Object,则子类返回值可以为Object或者其他Object子类
- 子类方法的修饰符应与父类方法修饰符一致或者比其更大
- 父类方法修饰符若为protected,则子类方法修饰符可以为protected或者public