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

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.

主站蜘蛛池模板: 洪雅县| 新昌县| 浏阳市| 鄂伦春自治旗| 巴林左旗| 鲁山县| 贵港市| 岐山县| 托克托县| 陈巴尔虎旗| 江西省| 开平市| 博白县| 邓州市| 贵溪市| 怀远县| 满城县| 墨脱县| 湘乡市| 信丰县| 共和县| 宣恩县| 犍为县| 靖宇县| 金塔县| 成武县| 富宁县| 章丘市| 庄浪县| 古田县| 商洛市| 苏尼特左旗| 腾冲县| 兴国县| 手游| 那曲县| 焉耆| 远安县| 达拉特旗| 莱西市| 屏南县|