如果子类中的方法与父类中的方法同名,且参数类型,参数个数,参数位置与父类完全一致时。这个时候,就说子类的方法完全覆盖了父类中的方法。比如:
class Father{
void sing(int i){ //父类的方法
System.out.println("I can sing "+i+" songs!");
}
}
class Son extends Father{
void sing(int i){ //子类重写覆盖了父类的方法
System.out.println("I can sing "+2*i+" songs!");
}
}
public class override extends Father{
public static void main(String[] args){
Father f = new Father();
f.sing(5); //调用父类的方法
Son s = new Son();
s.sing(5); //调用子类重写后的方法
}
}
本文通过一个具体例子详细介绍了在面向对象编程中子类如何通过方法覆盖来重写父类的方法。当子类的方法与父类的方法名称相同,并且参数类型、个数及位置完全一致时,即实现了方法覆盖。
1467

被折叠的 条评论
为什么被折叠?



