一、重写的定义
在子类中可以根据需要对从父类中继承来的方法进行改造,也称为方法的重置、覆盖。在程序执行时,子类的方法将覆盖父类的方法。在方法重写后,当创建子类对象,通过子类对象调用子父类中的同名同参数的方法时,实际执行的是子类重写父类的方法。
二、重写的规定
- 子类中的叫重写的方法,父类中的叫被重写的方法
权限修饰符 返回值类型 方法名(形参列表) throws 异常的类型{
//方法体
}
三、重写的要求
- 子类重写的方法的方法名和形参列表与父类被重写的方法的方法名和形参列表相同。
- 子类重写的方法的权限修饰符不小于父类被重写的方法的权限修饰符。
特殊情况:子类不能重写父类中声明为private权限的方法。 - 子类重写的方法的返回值类型:
①父类被重写的方法的返回值类型是void,则子类重写的方法的返回值类型只能是void。
②父类被重写的方法的返回值类型是A类型,则子类重写的方法的返回值类型可以是A类或A类的子类。
③父类被重写的方法的返回值类型是基本数据类型(比如double),则子类重写的方法的返回值类型必须是相同的基本数据类型(必须也是double)。 - 子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型。
四、重写的注意点
- 子类与父类中同名同参数的方法必须同时声明为非static的(即为重写),或者同时声明为static的(不是重写)。因为static方法是属于类的,子类无法覆盖父类的方法。
public class Person {
String name;
int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
void eat() {
System.out.println("吃饭");
}
public void walk(int distance) {
System.out.println("走路,走的距离是:" + distance + "公里");
show();
eat();
}
private void show() {
System.out.println("一个人");
}
public Object info() {
return null;
}
public double info1() {
return 1.0;
}
}
public class Student extends Person {
String major;
public Student() {
}
public Student(String major) {
this.major = major;
}
public void study() {
System.out.println("学习的专业是:" + major);
}
// 对父类中的eat()进行了重写
public void eat() {
System.out.println("学生应该多吃有营养的食物");
}
public void show() {
System.out.println("我是一个学生");
}
public String info() {
return null;
}
//The return type is incompatible with Person.info1()
// public int info1() {
// return 1;
// }
// public void walk(int distance){
// System.out.println("重写的方法");
// }
public void walk(int distance) {
System.out.println("重写的方法");
}
}