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

Static method in an interface

The static method in an interface is similar to the static method in a class. Users cannot override them. So even if a class implements an interface, it cannot override a static method of an interface.

Like a static method of a class, static method in an interface is called by using an interface name or class type reference, not using instance variables:

public interface MyInterface { 
    static String hello() 
    { 
       return "Inside static method in interface"; 
    } 
    void absmethod(); 
} 

Here is an interface with an abstract method and a static method:

public class MyInterfaceImpl implements MyInterface{ 
   @Override 
   public void absmethod() { 
      System.out.println("Abstract method implementaion in class");        
   } 
    
} 

Here is the class that implements the interface given previously, so to adhere to the contract it has to provide implementation of the abstract method as it is not an abstract class. However, it does not need to implement the static method.

Now, let's try to call the static method:

public class MyInterfaceDemo { 
public static void main(String[] args) { 
   System.out.println(MyInterface.hello()); // it works 
   MyInterfaceImpl obj =new MyInterfaceImpl(); 
   obj.hello(); // wont-complie 
} 
} 
 

So, calling the static method using the interface name reference works, but it does not work using the instance variable to a class that implements the interface.

主站蜘蛛池模板: 南澳县| 铁岭县| 咸阳市| 谢通门县| 乌兰县| 开封县| 濮阳县| 香港 | 兴仁县| 芷江| 缙云县| 壶关县| 瓮安县| 利津县| 克什克腾旗| 达拉特旗| 四平市| 杭州市| 荃湾区| 桑植县| 衡山县| 勐海县| 峨眉山市| 奎屯市| 南木林县| 梅州市| 泸州市| 仁布县| 定州市| 方正县| 鄂托克前旗| 天津市| 依兰县| 山东省| 铜山县| 调兵山市| 三江| 平陆县| 化德县| 长泰县| 易门县|