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

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.

主站蜘蛛池模板: 湟源县| 鹿泉市| 锦州市| 奉化市| 闽清县| 安新县| 陇西县| 抚顺县| 河源市| 扶沟县| 钦州市| 武安市| 永和县| 怀远县| 延长县| 大城县| 沙坪坝区| 台中市| 襄汾县| 双鸭山市| 迁西县| 铜川市| 阿图什市| 饶平县| 大荔县| 浮山县| 礼泉县| 寿阳县| 新河县| 钟祥市| 常熟市| 新蔡县| 遵义县| 临潭县| 南平市| 行唐县| 六枝特区| 雷波县| 德昌县| 黑水县| 福清市|