子类一定覆盖父类的同名方法吗?

子类对父类方法的覆盖是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,静态方法是属于类的,因此即使是子类对象拥有同名方法,也不是覆盖,调用静态方法是通过类实现,而不是通过对象实现的,因此通过对象实现的覆盖产生的多态对静态方法不适用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值