当⼀个⼦类继承了⼀个⽗类时,可以在⼦类中直接使⽤⽗类的属性和⽅法。如果⽗类的⽅法⽆法满⾜⼦类的需求,则可以在⼦类中对⽗类的⽅法进⾏改造,也称作重写(override)。重写是Java多态性的另⼀种体现。
重写的原则
重写的⽅法的签名必须要和被重写的⽅法的签名完全匹配
重写的⽅法的返回值必须和被重写的⽅法的返回⼀致或者是其⼦类;
重写的⽅法所抛出的异常必须和被重写⽅法的所抛出的异常⼀致,或者是其⼦类;
私有⽅法不能被重写
⼦类重写⽗类⽅法的过程中,可访问性只能⼀样或变的更公开。
public class Base {
public void print(){
System.out.println("In Base ");
}
public static void main(String[] args){
Son obj =new Son();
obj.print();
}
}
class Son extends Base {
// 覆盖⽗类的print()⽅法
public void print(){
System.out.println("In Son ");
}
}
//执⾏结果如下:
In Son