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.mzph.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;。 请你找出一个整数…