java 子接口中定义与父接口相同的方法

今天碰到一个很有意思的问题,在java中如果子接口中定义了与父接口中已经有的方法会发生什么事情呢?比如:

interface IRunnable extends Runnable{
	void run();
}

刚开始我还以为这样子的语法应该不能通过编译器,没有想到这样子做编译器并没有做出任何警告。

当然大多数情况下我们都不会这么做,因为这样做似乎没有什么意义。但为了真相,我还是做了个小实现:

public class InterfaceDebug{
	public static void main(String[] args){
		IRunnable irun1=new IRunnableImpl();
		irun1.run();
		Runnable irun=irun1;
		irun.run();
		irun=new IRunnableImpl2();
		irun.run();
	}
	
}
interface IRunnable extends Runnable{
	void run();
}
class IRunnableImpl implements IRunnable{
	public void run(){
		System.out.println("IRunnable of IRunnableImpl");
	}
}

class IRunnableImpl2 implements Runnable{
	public void run(){
		System.out.println("IRunnable of IRunnableImpl2"); 
	}
}

运行结果为:

IRunnable of IRunnableImpl
IRunnable of IRunnableImpl
IRunnable of IRunnableImpl2

这样子看到,在IRunnable中定义的run方法其实就是Runnable中的run,它们两是引用同一个东西的,并没有发生方法的覆盖。

转载于:https://www.cnblogs.com/mosmith/p/4196406.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值