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

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.

主站蜘蛛池模板: 莱阳市| 万安县| 抚顺市| 金堂县| 黄冈市| 浦江县| 普陀区| 嘉荫县| 巴中市| 齐齐哈尔市| 固始县| 宁海县| 乐都县| 化州市| 潜山县| 文水县| 龙里县| 开化县| 彰化县| 濮阳县| 丰镇市| 叙永县| 二手房| 东乌| 平原县| 绥阳县| 平山县| 济阳县| 贺兰县| 邵东县| 屏东市| 宝山区| 当阳市| 万州区| 宁陵县| 龙门县| 城固县| 岐山县| 文登市| 博罗县| 霍邱县|