注意事项和使用细节
方法重写也叫方法覆盖,需要满足下面的条件
1. 子类的方法的形参列表,方法名称,要和父类方法的参数,方法名完全一样。
2. 子类方法的返回类型和父类方法返回类型一样,或者是父类返回类型的子类
比如 父类 返回类型是Object,子类方法返回类型是String
3. 子类方法不能缩小父类方法的访问权限
public class Test {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
}
public class Animal {
Object eat(){子类能扩展父类方法的使用权限,但不能缩小
System.out.println("动物吃东西");
return null;
}
}
public class Dog extends Animal{
public String eat(){//String是Object的子类
System.out.println("小狗吃东西");
return null;
}
}