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

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.

主站蜘蛛池模板: 景宁| 曲松县| 宿迁市| 临城县| 屯留县| 文化| 马公市| 亚东县| 佛冈县| 平果县| 兴化市| 云阳县| 泌阳县| 沁源县| 原阳县| 卓尼县| 松阳县| 莎车县| 大庆市| 喀喇| 丹江口市| 平泉县| 武宁县| 崇礼县| 四子王旗| 诸城市| 汕尾市| 安阳市| 盐津县| 西吉县| 汤原县| 三门峡市| 望谟县| 盐池县| 于田县| 阿拉善左旗| 什邡市| 潞西市| 定结县| 万宁市| 玉溪市|