官术网_书友最值得收藏!

What if a class implements two interfaces which have default methods with same name and signature?

Interfaces in Java are used to provide multiple inheritances. Classes can implement more than one interface. As interface can consist of default methods in Java 8, which a class does not necessarily need to implement. We can have two interfaces that have default methods with the same name and signature.

Let's create two interfaces with the same default method:

public interface Interface1 { 
   default void hello(){ 
      System.out.println("Hello from Interface1"); 
   } 
} 
 
public interface Interface2 { 
   default void hello(){ 
      System.out.println("Hello from Interface1"); 
   } 
} 

So, we have two interfaces with the default method hello with the same signature:

public class InterfaceImpl implements Interface1,Interface2{ 
   @Override 
   public void hello() { 
      Interface1.super.hello(); 
   } 
} 

Now, once you create a class that implements both of these interfaces, the compiler will force you to override the hello method. You can call hello of any of the interfaces if you want using the syntax given previously or you can given a different implementation to it.

主站蜘蛛池模板: 贞丰县| 大英县| 双流县| 永平县| 玉门市| 澄城县| 德阳市| 福清市| 汽车| 广水市| 巴楚县| 高密市| 四子王旗| 马边| 新蔡县| 宣威市| 达拉特旗| 呼和浩特市| 保康县| 象州县| 平南县| 宜川县| 房产| 巴马| 谢通门县| 武安市| 阿拉善右旗| 孟津县| 河津市| 象州县| 保德县| 兴化市| 水城县| 建平县| 大冶市| 华阴市| 白城市| 洛阳市| 荔波县| 莱西市| 湖南省|