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

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.

主站蜘蛛池模板: 宝丰县| 清徐县| 若羌县| 大田县| 武宣县| 德安县| 西青区| 宁远县| 光泽县| 灵武市| 南川市| 珲春市| 嘉峪关市| 纳雍县| 东丽区| 兰溪市| 普兰店市| 勐海县| 西青区| 长海县| 石嘴山市| 肃宁县| 新乡市| 镇平县| 北票市| 怀化市| 陆丰市| 都匀市| 凤翔县| 宣城市| 博罗县| 金沙县| 广宗县| 板桥市| 英吉沙县| 沙河市| 普格县| 化州市| 永胜县| 武安市| 南皮县|