- Apache Spark 2.x for Java Developers
- Sourav Gulati Sumit Kumar
- 215字
- 2021-07-02 19:01:55
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.
- 程序員修煉之道:程序設計入門30講
- OpenDaylight Cookbook
- 造個小程序:與微信一起干件正經事兒
- Learning ArcGIS Pro 2
- 概率成形編碼調制技術理論及應用
- 零基礎入門學習Python(第2版)
- SQL Server與JSP動態網站開發
- 常用工具軟件立體化教程(微課版)
- Bootstrap 4 Cookbook
- Node.js開發指南
- 創意UI:Photoshop玩轉APP設計
- 監控的藝術:云原生時代的監控框架
- Modernizing Legacy Applications in PHP
- 計算機程序的構造和解釋(JavaScript版)
- Improving your Penetration Testing Skills