子类对父类方法的覆盖是Java实现多态的重要手段,但是如果运行下面一段代码,结果很奇异
package staticTest;
import anotherPackage.*;
//
//父子类方法同名一定覆盖吗
public class Father {
public void say() {
System.out.println("I'm father say");
}
private void hello() {
System.out.println("I'm father hello");
}
void sayToAnotherPackage() {
System.out.println("I'm father another say");
}
public static void hellostatic() {
System.out.println("I'm father static hello");
}
public static void main(String[] args){
Father samePackage=new SonSamePackage();
samePackage.say();//这个方法是正常的多态,没有什么问题
samePackage.hello();//这个方法实际是子类访问不到的private限制,因此无法覆盖
samePackage.hellostatic();//静态方法属于类,因此最终执行的是samePackage的编译时类型,而不是运行时类型来执行
//因此执行的仍然是父类的
Father anotherPackage=new SonAnotherPackage();
anotherPackage.sayToAnotherPackage();//默认访问权限,导致另一包中的子类无法访问要覆盖的sayToAnotherPackage方法,因此无法覆盖,
//故,执行该操作的依然是父类的sayToAnotherPackage方法
}
}
class SonSamePackage extends Father {
public void say() {
System.out.println("I'm SonSamePackage say");
}
private void hello() {
System.out.println("I'm SonSamePackage hello");
}
void sayToAnotherPackage() {
System.out.println("I'm SonSamePackage another say");
}
public static void hellostatic() {
System.out.println("I'm SonSamePackage static hello");
}
}
package anotherPackage;
//一定要放在另外一个包中,否则运行结果与文章说明不一致。
import staticTest.*;
public class SonAnotherPackage extends Father{
public void say(){
System.out.println("I'm SonAnotherPackage say");
}
public void hello(){
System.out.println("I'm SonAnotherPackage hello");
}
void sayToAnotherPackage(){
System.out.println("I'm SonAnotherPackage another say");
}
public static void hellostatic(){
System.out.println("I'm SonAnotherPackage static hello");
}
}
运行Father类的main方法,可以看到如下结果
I'm SonSamePackage say
I'm father hello
I'm father static hello
I'm father another say
而不是预想中的执行子类方法。
通过查看注释,可以有以下结论
1,Java中父类的方法能不能被子类覆盖,取决于子类能不能访问到父类的对应方法:如private、 默认访问权限的约束
2,静态方法是属于类的,因此即使是子类对象拥有同名方法,也不是覆盖,调用静态方法是通过类实现,而不是通过对象实现的,因此通过对象实现的覆盖产生的多态对静态方法不适用。