java請求接口示例_用示例解釋Java接口

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請求接口示例

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390665.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390665.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390665.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

如何建立搜索引擎_如何建立搜尋引擎

如何建立搜索引擎This article outlines one of the most important search algorithms used today and demonstrates how to implement it in Python in just a few lines of code.本文概述了當今使用的最重要的搜索算法之一,并演示了如何僅用幾行代碼就可以在Pyth…

用Docker自動構建紙殼CMS

紙殼CMS可以運行在Docker上,接下來看看如何自動構建紙殼CMS的Docker Image。我們希望的是在代碼提交到GitHub以后,容器鏡像服務可以自動構建Docker Image,構建好以后,就可以直接拿這個Docker Image來運行了。 Dockerfile 最重要的…

Linux學習筆記15—RPM包的安裝OR源碼包的安裝

RPM安裝命令1、 安裝一個rpm包rpm –ivh 包名“-i” : 安裝的意思“-v” : 可視化“-h” : 顯示安裝進度另外在安裝一個rpm包時常用的附帶參數有:--force : 強制安裝,即使覆蓋屬于其他包的文件也要安裝--nodeps : 當要安裝的rpm包依賴其他包時&#xff0…

leetcode 518. 零錢兌換 II

給定不同面額的硬幣和一個總金額。寫出函數來計算可以湊成總金額的硬幣組合數。假設每一種面額的硬幣有無限個。 示例 1: 輸入: amount 5, coins [1, 2, 5] 輸出: 4 解釋: 有四種方式可以湊成總金額: 55 5221 52111 511111 示例 2: 輸入: amount 3, coins [2] 輸出: 0 解…

軟件測試中什么是正交實驗法_軟件工程中的正交性

軟件測試中什么是正交實驗法正交性 (Orthogonality) In software engineering, a system is considered orthogonal if changing one of its components changes the state of that component only. 在軟件工程中,如果更改系統的組件之一僅更改該組件的狀態&#xf…

leetcode 279. 完全平方數(dp)

題目一 給定正整數 n,找到若干個完全平方數(比如 1, 4, 9, 16, …)使得它們的和等于 n。你需要讓組成和的完全平方數的個數最少。 給你一個整數 n ,返回和為 n 的完全平方數的 最少數量 。 完全平方數 是一個整數,其…

github代碼_GitHub啟動代碼空間

github代碼Codespaces works like a virtual Integrated Development Environment (IDE) on the cloud.代碼空間的工作方式類似于云上的虛擬集成開發環境(IDE)。 Until now, you had to make a pull request to contribute to a project. This required setting up the enviro…

php變量

什么叫變量&#xff1f; 變量可以通過變量名訪問。在指令式語言中&#xff0c;變量通常是可變的&#xff1b; 這里就先這么簡單理解&#xff0c;通過對語言的研究會更加的理解變量的其他意義。 在PHP中變量是用于存儲信息的"容器"&#xff1a; <?php $x5; $y6;…

js將base64做UrlEncode轉碼

使用 encodeURIComponent() 其詳細介紹 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent var base64 &#xff08;base64值&#xff09;encodeURIComponent(base64 ) //轉化 轉載于:https://www.cnblogs.com/xll-qg/p…

引用自己創建的css樣式表_如何使用CSS創建聯系表

引用自己創建的css樣式表First we create the HTML elements - input fields for First Name, Last Name, Email and a Text Area for the message.首先&#xff0c;我們創建HTML元素-名字&#xff0c;姓氏&#xff0c;電子郵件和消息的文本區域的輸入字段。 Later we apply C…

leetcode 1449. 數位成本和為目標值的最大數字(dp)

這是我參與更文挑戰的第12天 &#xff0c;活動詳情查看更文挑戰 題目 給你一個整數數組 cost 和一個整數 target 。請你返回滿足如下規則可以得到的 最大 整數&#xff1a; 給當前結果添加一個數位&#xff08;i 1&#xff09;的成本為 cost[i] &#xff08;cost 數組下標…

風能matlab仿真_風能產量預測—深度學習項目

風能matlab仿真DL DATATHON- AI4ImpactDL DATATHON- AI4影響 Published by Team AI Traders — Suyash Lohia, Nguyen Khoi Phan, Nikunj Taneja, Naman Agarwal and Mihir GuptaAI交易員團隊發布 -Suyash Lohia&#xff0c;Nguyen Khoi Phan&#xff0c;Nikonj Taneja&#x…

android JNI調用(Android Studio 3.0.1)(轉)

最近回頭復習了一下android 的jni調用&#xff0c;卻發現按以前的方法調用失敗&#xff0c;一怒之下就重新摸索&#xff0c;碰了幾次壁&#xff0c;發現網上好多教程都不能成功調用&#xff0c;于是記錄一下現在AS版本成功好用的調用方法。 這里設定你的ndk已經下載并且設置沒問…

安卓源碼 代號,標簽和內部版本號

SetupSecurityPortingTuningCompatibilityReference轉到源代碼Getting Started OverviewCodelines, Branches, and ReleasesCodenames, Tags, and Build NumbersProject RolesBrand GuidelinesLicensesFAQSite UpdatesDownloading and Building RequirementsEstablishing a Bui…

git 列出標簽_Git標簽介紹:如何在Git中列出,創建,刪除和顯示標簽

git 列出標簽Tagging lets developers mark important checkpoints in the course of their projects development. For instance, software release versions can be tagged. (Ex: v1.3.2) It essentially allows you to give a commit a special name(tag).通過標記&#xff…

leetcode 278. 第一個錯誤的版本(二分)

題目 你是產品經理&#xff0c;目前正在帶領一個團隊開發新的產品。不幸的是&#xff0c;你的產品的最新版本沒有通過質量檢測。由于每個版本都是基于之前的版本開發的&#xff0c;所以錯誤的版本之后的所有版本都是錯的。 假設你有 n 個版本 [1, 2, …, n]&#xff0c;你想找…

騰訊哈勃_用Python的黑客統計資料重新審視哈勃定律

騰訊哈勃Simple OLS Regression, Pairs Bootstrap Resampling, and Hypothesis Testing to observe the effect of Hubble’s Law in Python.通過簡單的OLS回歸&#xff0c;配對Bootstrap重采樣和假設檢驗來觀察哈勃定律在Python中的效果。 In this post, we will revisit Hub…

JAVA中動態編譯的簡單使用

一、引用庫 pom文件中申明如下&#xff1a; <dependencies><!-- https://mvnrepository.com/artifact/junit/junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><…

程序員實用小程序_我從閱讀《實用程序員》中學到了什么

程序員實用小程序In short: old but gold.簡而言之&#xff1a;古老而又黃金。 Published in 1999, The Pragmatic Programmer is a book about how to become a Pragmatic Programmer. Which really means a ‘Good Programmer’. 《實用程序員》于1999年出版&#xff0c;是一…

leetcode 5786. 可移除字符的最大數目(二分法)

題目 給你兩個字符串 s 和 p &#xff0c;其中 p 是 s 的一個 子序列 。同時&#xff0c;給你一個元素 互不相同 且下標 從 0 開始 計數的整數數組 removable &#xff0c;該數組是 s 中下標的一個子集&#xff08;s 的下標也 從 0 開始 計數&#xff09;。 請你找出一個整數…