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

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.

主站蜘蛛池模板: 古交市| 合江县| 兴山县| 交口县| 池州市| 花垣县| 潮州市| 玉溪市| 毕节市| 鞍山市| 鄂温| 海晏县| 綦江县| 潍坊市| 克什克腾旗| 德清县| 体育| 望谟县| 修水县| 潜山县| 乌恰县| 广宁县| 当阳市| 绥德县| 阳山县| 乌拉特前旗| 梅州市| 沙湾县| 南平市| 江陵县| 沙坪坝区| 万载县| 嘉鱼县| 新和县| 四子王旗| 贵港市| 汕头市| 昌乐县| 铁岭市| 麻栗坡县| 新晃|