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

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.

主站蜘蛛池模板: 金乡县| 华池县| 女性| 镇安县| 龙门县| 呼和浩特市| 班玛县| 莆田市| 镇安县| 肇东市| 沾益县| 上饶县| 新邵县| 乐亭县| 阆中市| 阿拉善右旗| 喜德县| 崇礼县| 玉环县| 安丘市| 湖北省| 安丘市| 西华县| 安阳县| 衡山县| 合山市| 临泽县| 和政县| 图们市| 黑龙江省| 宝应县| 鄂尔多斯市| 霍州市| 台湾省| 黔西县| 浦城县| 阿拉善盟| 吉木乃县| 紫金县| 抚远县| 凭祥市|