java請求接口示例
介面 (Interfaces)
Interface in Java is a bit like the Class, but with a significant difference: an interface
can only have method signatures, fields and default methods. Since Java 8, you can also create default methods. In the next block you can see an example of interface:
Java中的接口有點類似于Class,但是有一個顯著的區別: interface
只能具有方法簽名,字段和默認方法。 從Java 8開始,您還可以創建默認方法 。 在下一個塊中,您可以看到接口的示例:
public interface Vehicle {public String licensePlate = "";public float maxVelpublic void start();public void stop();default void blowHorn(){System.out.println("Blowing horn");}
}
The interface above contains two fields, two methods, and a default method. Alone, it is not of much use, but they are usually used along with Classes. How? Simple, you have to make sure some class implements
it.
上面的界面包含兩個字段,兩個方法和一個默認方法。 單獨使用它并沒有多大用處,但是它們通常與類一起使用。 怎么樣? 很簡單,您必須確保某些類可以implements
它。
public class Car implements Vehicle {public void start() {System.out.println("starting engine...");}public void stop() {System.out.println("stopping engine...");}
}
Now, there is a ground rule: The Class must implement all of the methods in the Interface. The methods must have the exact same signature (name, parameters and exceptions) as described in the interface. The class does not need to declare the fields though, only the methods.
現在,有一條基本規則 :類必須在接口中實現所有方法。 這些方法必須具有與接口中所述完全相同的簽名(名稱,參數和異常)。 類并不需要聲明雖然場,只有方法。
接口實例 (Instances of an Interface)
Once you create a Java Class which implements
any Interface, the object instance can be referenced as an instance of the Interface. This concept is similar to that of Inheritance instantiation.
一旦創建了implements
任何接口的Java類,就可以將對象實例引用為接口的實例。 這個概念類似于繼承實例化。
// following our previous exampleVehicle tesla = new Car();tesla.start(); // starting engine ...
An Interface can not contain a constructor methods,therefore,you can not create an instance of an Interface itself. You must create an instance of some class implementing an Interface to reference it. Think of interfaces as a blank contract form, or a template.
接口不能包含構造函數方法,因此,您不能創建接口本身的實例。 您必須創建一些實現接口的類的實例來引用它。 可以將接口視為空白合同形式或模板。
What can you do with this feature? Polymorphism! You can use only interfaces to refer to object instances!
您可以使用此功能做什么? 多態! 您只能使用接口來引用對象實例!
class Truck implements Vehicle {public void start() {System.out.println("starting truck engine...");}public void stop() {System.out.println("stopping truck engine...");}
}class Starter {// static method, can be called without instantiating the classpublic static void startEngine(Vehicle vehicle) {vehicle.start();}
}Vehicle tesla = new Car();
Vehicle tata = new Truck();Starter.startEngine(tesla); // starting engine ...
Starter.startEngine(tata); // starting truck engine ...
但是多個接口呢? (But how about multiple interfaces?)
Yes, you can implement multiple Interfaces in a single class. While in Inheritance within Classes you were restricted to inherit only one class, here you can extend any number of interfaces. But do not forget to implement all of the methods of all the Interfaces, otherwise compilation will fail!
是的,您可以在一個類中實現多個接口。 而在繼承類中,你被限制只繼承一個類,在這里你可以擴展任意數量的接口。 但是不要忘記實現所有接口的所有方法,否則編譯將失敗!
public interface GPS {public void getCoordinates();
}public interface Radio {public void startRadio();public void stopRadio();
}public class Smartphone implements GPS,Radio {public void getCoordinates() {// return some coordinates}public void startRadio() {// start Radio}public void stopRadio() {// stop Radio}
}
接口的一些功能 (Some features of Interfaces)
- You can place variables within an Interface, although it won’t be a sensible decision as Classes are not bound to have the same variable. In short, avoid placing variables! 您可以在接口中放置變量,盡管由于類不具有相同的變量,這并不是明智的決定。 簡而言之,避免放置變量!
All variables and methods in an Interface are public, even if you leave out the
public
keyword.即使省略了
public
關鍵字,Interface中的所有變量和方法都是公共的。- An Interface cannot specify the implementation of a particular method. Its up to the Classes to do it. Although there has been a recent exception (see below). 接口無法指定特定方法的實現。 由班級來決定。 盡管最近有例外(請參閱下文)。
If a Class implements multiple Interfaces, then there is a remote chance of method signature overlap. Since Java does not allow multiple methods of the exact same signature, this can lead to problems. See this question for more info.
如果一個類實現多個接口,則方法簽名重疊的可能性很小。 由于Java不允許使用具有完全相同簽名的多種方法,因此可能導致問題。 有關更多信息,請參見此問題 。
接口默認方法 (Interface Default Methods)
Before Java 8, we had no way to direct an Interface to have a particular method implementation. This lead to lot of confusion and code breaks if an Interface definition is suddenly changed.
在Java 8之前,我們無法指導Interface具有特定的方法實現。 如果突然更改接口定義,這會導致很多混亂和代碼中斷。
Suppose, you wrote an open source library, which contains an Interface. Say, your clients, i.e. practically all developers around the world, are using it heavily and are happy. Now you have had to upgrade the library by adding a new method definition to the Interface to support a new feature. But that would break all builds since all Classes implementing that Interface have to change now. What a catastrophe!
假設您編寫了一個包含接口的開源庫。 說,您的客戶,即幾乎全世界的所有開發人員,都在大量使用它并感到高興。 現在,您必須通過向接口添加新的方法定義以支持新功能來升級庫。 但這將破壞所有構建,因為實現該接口的所有類都必須立即更改。 真是大災難!
Thankfully, Java 8 now provides us default
methods for Interfaces. A default
method can contain its own implementation directly within the Interface! So, if a Class does not implement a default method, the compiler will take the implementation mentioned within the Interface. Nice, isn’t it? So in your library, you may add any number of default methods in interfaces without the fear of breaking anything!
幸運的是,Java 8現在為我們提供了接口的default
方法。 default
方法可以 直接在接口中包含其自己的實現! 因此,如果Class不實現默認方法,則編譯器將采用Interface中提到的實現。 很好,不是嗎? 因此,在您的庫中,您可以在接口中添加任意數量的默認方法,而不必擔心會破壞任何內容!
public interface GPS {public void getCoordinates();default public void getRoughCoordinates() {// implementation to return coordinates from rough sources// such as wifi & mobileSystem.out.println("Fetching rough coordinates...");}
}public interface Radio {public void startRadio();public void stopRadio();
}public class Smartphone implements GPS,Radio {public void getCoordinates() {// return some coordinates}public void startRadio() {// start Radio}public void stopRadio() {// stop Radio}// no implementation of getRoughCoordinates()
}Smartphone motoG = new Smartphone();
motog.getRoughCoordinates(); // Fetching rough coordinates...
But, what happens if two interfaces have the same method signature?
但是,如果兩個接口具有相同的方法簽名怎么辦?
Awesome question. In that case, if you do not provide the implementation in the Class, poor compiler will get confused and simply fail! You have to provide a default method implementation within the Class also. There is also a nifty way using super
to call which implementation you like:
很棒的問題。 在這種情況下,如果您未在Class中提供實現,則可憐的編譯器會感到困惑,并且只會失敗! 您還必須在Class中提供默認的方法實現。 還有一種使用super
調用您喜歡的實現的好方法:
public interface Radio {// public void startRadio();// public void stopRadio();default public void next() {System.out.println("Next from Radio");}
}public interface MusicPlayer {// public void start();// public void pause();// public void stop();default public void next() {System.out.println("Next from MusicPlayer");}
}public class Smartphone implements Radio, MusicPlayer {public void next() {// Suppose you want to call MusicPlayer nextMusicPlayer.super.next();}
}Smartphone motoG = new Smartphone();
motoG.next(); // Next from MusicPlayer
接口中的靜態方法 (Static Methods in Interfaces)
Also new to Java 8 is the ability to add static methods to interfaces. Static methods in interfaces are almost identical to static methods in concrete classes. The only big difference is that static
methods are not inherited in the classes that implement the interface. This means that the interface is referenced when calling the static method not the class that implements it.
Java 8的另一個新功能是可以向接口添加靜態方法。 接口中的靜態方法幾乎與具體類中的靜態方法相同。 唯一的不同是static
方法不會在實現接口的類中繼承。 這意味著在調用靜態方法而不是實現它的類時,將引用該接口。
interface MusicPlayer {public static void commercial(String sponsor) {System.out.println("Now for a message brought to you by " + sponsor);}public void play();
}class Smartphone implements MusicPlayer {public void play() {System.out.println("Playing from smartphone");}
}class Main {public static void main(String[] args) {Smartphone motoG = new Smartphone();MusicPlayer.commercial("Motorola"); // Called on interface not on implementing class// motoG.commercial("Motorola"); // This would cause a compilation error }
}
繼承接口 (Inheriting an Interface)
It is also possible in Java for an Interface to inherit another Interface, by using, you guessed it, extends
keyword:
在Java中,接口還可以通過使用您猜想的extends
關鍵字來繼承另一個接口:
public interface Player {public void start();public void pause();public void stop();
}public interface MusicPlayer extends Player {default public void next() {System.out.println("Next from MusicPlayer");}
}
That means, the Class implementing MusicPlayer
Interface has to implement all methods of MusicPlayer
as well as Player
:
這意味著,類實現MusicPlayer
接口必須實現的所有方法MusicPlayer
以及Player
:
public class SmartPhone implements MusicPlayer {public void start() {System.out.println("start");}public void stop() {System.out.println("stop");}public void pause() {System.out.println("pause");}
}
So now you have a good grasp of Java interfaces! Go learn about Abstract Classes to see how Java gives you yet another way to define contracts.
現在,您已經掌握了Java接口! 進一步了解抽象類,了解Java如何為您提供另一種定義合同的方式。
翻譯自: https://www.freecodecamp.org/news/java-interfaces-explained-with-examples/
java請求接口示例