Java中的接口是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1321122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is an interface in Java?
提问by Imagist
Just as a counterpoint to this question: what is an interface in Java?
正如这个问题的对立面:Java 中的接口是什么?
采纳答案by Imagist
An interface is a special form of an abstract class which does not implement any methods. In Java, you create an interface like this:
接口是抽象类的一种特殊形式,它不实现任何方法。在 Java 中,您可以创建这样的接口:
interface Interface
{
void interfaceMethod();
}
Since the interface can't implement any methods, it's implied that the entire thing, including all the methods, are both public and abstract (abstract in Java terms means "not implemented by this class"). So the interface above is identical to the interface below:
由于接口不能实现任何方法,这意味着整个事物,包括所有方法,都是公共的和抽象的(Java 术语中的抽象意味着“这个类没有实现”)。所以上面的界面和下面的界面是一样的:
public interface Interface
{
abstract public void interfaceMethod();
}
To use this interface, you simply need to implement the interface. Many classes can implement an interface, and a class can implement many interfaces:
要使用此接口,您只需实现该接口。很多类可以实现一个接口,一个类可以实现很多接口:
interface InterfaceA
{
void interfaceMethodA();
}
interface InterfaceB
{
void interfaceMethodB();
}
public class ImplementingClassA
implements InterfaceA, InterfaceB
{
public void interfaceMethodA()
{
System.out.println("interfaceA, interfaceMethodA, implementation A");
}
public void interfaceMethodB()
{
System.out.println("interfaceB, interfaceMethodB, implementation A");
}
}
public class ImplementingClassB
implements InterfaceA, InterfaceB
{
public void interfaceMethodA()
{
System.out.println("interfaceA, interfaceMethodA, implementation B");
}
public void interfaceMethodB()
{
System.out.println("interfaceB, interfaceMethodB, implementation B");
}
}
Now if you wanted you could write a method like this:
现在,如果您愿意,可以编写这样的方法:
public void testInterfaces()
{
ImplementingClassA u = new ImplementingClassA();
ImplementingClassB v = new ImplementingClassB();
InterfaceA w = new ImplementingClassA();
InterfaceA x = new ImplementingClassB();
InterfaceB y = new ImplementingClassA();
InterfaceB z = new ImplementingClassB();
u.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation A"
u.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation A"
v.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation B"
v.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation B"
w.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation A"
x.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation B"
y.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation A"
z.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation B"
}
However, you could neverdo the following:
但是,您永远不能执行以下操作:
public void testInterfaces()
{
InterfaceA y = new ImplementingClassA();
InterfaceB z = new ImplementingClassB();
y.interfaceMethodB(); // ERROR!
z.interfaceMethodA(); // ERROR!
}
The reason you can't do this is that y
is of type interfaceA
, and there is no interfaceMethodB()
in interfaceA
. Likewise, z
is of type interfaceB
and there is no interfaceMethodA()
in interfaceB
.
你不能这样做的原因y
是 type interfaceA
,并且没有interfaceMethodB()
in interfaceA
。同样,z
is 是类型interfaceB
并且没有interfaceMethodA()
in interfaceB
。
I mentioned earlier that interfaces are just a special form of an abstract class. To illustrate that point, look at the following code.
我之前提到接口只是抽象类的一种特殊形式。为了说明这一点,请查看以下代码。
interface Interface
{
void abstractMethod();
}
abstract public class AbstractClass
{
abstract public void abstractMethod();
}
You would inherit from these classes almost exactly the same way:
您将以几乎完全相同的方式从这些类继承:
public class InheritsFromInterface
implements Interface
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}
public class InteritsFromAbstractClass
extends AbstractClass
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}
In fact, you could even change the interface and the abstract class like this:
实际上,您甚至可以像这样更改接口和抽象类:
interface Interface
{
void abstractMethod();
}
abstract public class AbstractClass
implements Interface
{
abstract public void abstractMethod();
}
public class InheritsFromInterfaceAndAbstractClass
extends AbstractClass implements Interface
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}
However, there are two differences between interfaces and abstract classes.
但是,接口和抽象类之间有两个区别。
The first difference is that interfaces cannot implement methods.
第一个区别是接口不能实现方法。
interface Interface
{
public void implementedMethod()
{
System.out.println("implementedMethod()");
}
}
The interface above generates a compiler error because it has an implementation for implementedMethod()
. If you wanted to implement the method but not be able to instantiate the class, you would have to do it like this:
上面的接口会生成编译器错误,因为它具有implementedMethod()
. 如果您想实现该方法但无法实例化该类,则必须这样做:
abstract public class AbstractClass
{
public void implementedMethod()
{
System.out.println("implementedMethod()");
}
}
That's not much of an abstract class because none of its members are abstract, but it is legal Java.
这不是一个抽象类,因为它的成员都不是抽象的,但它是合法的 Java。
The other difference between interfaces and abstract classes is that a class can inherit from multiple interfaces, but can only inherit from one abstract class.
接口和抽象类的另一个区别是一个类可以继承多个接口,但只能继承一个抽象类。
abstract public class AbstractClassA { }
abstract public class AbstractClassB { }
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }
The code above generates a compiler error, not because the classes are all empty, but because InheritsFromTwoAbstractClasses
is trying to inherit from two abstract classes, which is illegal. The following is perfectly legal.
上面的代码产生编译错误,不是因为类都是空的,而是因为InheritsFromTwoAbstractClasses
试图从两个抽象类继承,这是非法的。以下是完全合法的。
interface InterfaceA { }
interface InterfaceB { }
public class InheritsFromTwoInterfaces
implements InterfaceA, InterfaceB
{ }
The first difference between interfaces and abstract classes is the reason for the second difference. Take a look at the following code.
接口和抽象类之间的第一个区别是第二个区别的原因。看看下面的代码。
interface InterfaceA
{
void method();
}
interface InterfaceB
{
void method();
}
public class InheritsFromTwoInterfaces
implements InterfaceA, InterfaceB
{
void method() { System.out.println("method()"); }
}
There's no problem with the code above because InterfaceA
and InterfaceB
don't have anything to hide. It's easy to tell that a call to method
will print "method()".
有上面,因为代码没有问题InterfaceA
,并InterfaceB
没有什么要隐瞒。很容易判断调用method
将打印“method()”。
Now look at the following code:
现在看下面的代码:
abstract public class AbstractClassA
{
void method() { System.out.println("Hello"); }
}
abstract public class AbstractClassB
{
void method() { System.out.println("Goodbye"); }
}
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }
This is exactly the same as our other example, except that because we're allowed to implement methods in abstract classes, we did, and because we don't have to implement already-implemented methods in an inheriting class, we didn't. But you may have noticed, there's a problem. What happens when we call new InheritsFromTwoAbstractClasses().method()
? Does it print "Hello" or "Goodbye"? You probably don't know, and neither does the Java compiler. Another language, C++ allowed this kind of inheritance and they resolved these issues in ways that were often very complicated. To avoid this kind of trouble, Java decided to make this "multiple inheritance" illegal.
这与我们的另一个示例完全相同,除了因为我们允许在抽象类中实现方法,我们做到了,并且因为我们不必在继承类中实现已经实现的方法,所以我们没有。但你可能已经注意到,有一个问题。当我们打电话时会发生什么new InheritsFromTwoAbstractClasses().method()
?它打印“你好”还是“再见”?您可能不知道,Java 编译器也不知道。另一种语言,C++ 允许这种继承,它们以通常非常复杂的方式解决了这些问题。为了避免这种麻烦,Java 决定将这种“多重继承”定为非法。
The downside to Java's solution that the following can't be done:
Java 解决方案的缺点是无法完成以下操作:
abstract public class AbstractClassA
{
void hi() { System.out.println("Hello"); }
}
abstract public class AbstractClassB
{
void bye() { System.out.println("Goodbye"); }
}
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }
AbstractClassA
and AbstractClassB
are "mixins" or classes that aren't intended to be instantiated but add functionality to the classes that they are "mixed into" through inheritance. There's obviously no problem figuring out what happens if you call new InheritsFromTwoAbstractClasses().hi()
or new InheritsFromTwoAbstractClasses().bye()
, but you can't do that because Java doesn't allow it.
AbstractClassA
并且AbstractClassB
是“混入”或不打算实例化的类,而是向通过继承“混入”的类添加功能。弄清楚如果调用new InheritsFromTwoAbstractClasses().hi()
or会发生什么显然没有问题new InheritsFromTwoAbstractClasses().bye()
,但是您不能这样做,因为 Java 不允许这样做。
(I know this is a long post, so if there are any mistakes in it please let me know and I will correct them.)
(我知道这是一篇很长的文章,所以如果其中有任何错误,请告诉我,我会更正。)
回答by Ketan G
An interfacein java is a blueprint of a class. It has static constants and abstract methods only.The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java. An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors(Abstract Methods) that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.Since multiple inheritance is not allowed in java so interface is only way to implement multiple inheritance.Here is an example for understanding interface
一个接口在java中是一个类的蓝图。它只有静态常量和抽象方法。java中的接口是一种实现完全抽象的机制。java接口中只能有抽象方法,不能有方法体。它用于在 Java 中实现完全抽象和多重继承。接口是抽象方法的集合。一个类实现了一个接口,从而继承了接口的抽象方法。接口不是类。编写接口类似于编写类,但它们是两个不同的概念。类描述了对象的属性和行为。接口包含类实现的行为(抽象方法)。除非实现接口的类是抽象类,否则接口的所有方法都需要在类中定义。这是一个理解界面的例子
interface Printable{
void print();
}
interface Showable{
void print();
}
class testinterface1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
testinterface1 obj = new testinterface1();
obj.print();
}
}
回答by Revathi Bala
Interface is the blueprint of an class.
接口是一个类的蓝图。
There is one oop's concept called Data abstractionunder that there are two categories one is abstract classand other one is interface.
oop 的一个概念叫做Data abstraction,它分为两类,一类是抽象类,一类是接口。
Abstract class achieves only partial abstraction but interface achieves full abstraction.
抽象类只实现了部分抽象,而接口实现了完全抽象。
In interface there is only abstract methods and final variables..you can extends any number of interface and you can implement any number of classes.
在接口中只有抽象方法和最终变量......你可以扩展任意数量的接口,你可以实现任意数量的类。
If any class is implementing the interface then the class must implements the abstract methods too
如果任何类正在实现接口,则该类也必须实现抽象方法
Interface cannot be instantiated.
接口不能被实例化。
interface A() {
void print()
}
回答by Ravindra babu
This question is 6 years old and lot of things have changed the definition of interface over the years.
这个问题已经有 6 年的历史了,多年来很多事情都改变了界面的定义。
From oracle documentationpage ( post Java 8 release) :
从 oracle文档页面(发布 Java 8 版本):
In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
在 Java 编程语言中,接口是一种引用类型,类似于类,只能包含常量、方法签名、默认方法、静态方法和嵌套类型。方法体仅存在于默认方法和静态方法中。接口不能被实例化——它们只能由类实现或由其他接口扩展。
Have a look at related SE questions for better explanation:
查看相关的 SE 问题以获得更好的解释:
Is there more to an interface than having the correct methods
What is the difference between an interface and abstract class?
回答by S R Chaitanya
What it is
An interfaceis a reference type, just like a classis. These are the two main reference types in Java.
它是什么
一个接口是引用类型,就像一类是。这是 Java 中的两种主要引用类型。
What it contains
An interfacecan contain a subset of what a normal classcan contain. This includes everything that is static
, both methods and variables, and non-static
method declarations. It is not allowed to have non-static
variables.
A declaration of a method differs from a normal method in several things; here is one as an example:
它所包含
的接口可以包含一个什么样的标准的子集类可以包含。这包括所有内容static
,包括方法和变量,以及非static
方法声明。不允许有非static
变量。
方法的声明在几个方面与普通方法不同;这是一个例子:
[public] [abstract] ReturnType methodName();
These declarations can be marked as public
and abstract
, as represented with [optional braces]
. It is not necessary to do so, as it is the default. private
, protected
, package-private
(aka. nothing) and the final
modifier are not allowed and marked as a compiler error. They have not implementation, so there is a semicolon instead of curly braces.
这些声明可以标记为public
和abstract
,用 表示[optional braces]
。没有必要这样做,因为它是默认设置。private
, protected
, package-private
(aka. nothing) 和final
修饰符不被允许并被标记为编译器错误。他们没有实现,所以有一个分号而不是花括号。
As of Java 8, they canhold non-static
methods withan implementation, these have to be marked with the default
modifier. However, the same restrictions as to the other modifiers apply (adding that strictfp
is now valid and abstract
is no more).
从 Java 8 开始,它们可以包含具有实现的非static
方法,这些必须用修饰符标记。但是,与其他修饰符相同的限制适用(添加现在有效且不再有效)。default
strictfp
abstract
What it's useful for
One of its uses is for it to be used as a face for a service. When two parties work together to form a service-requester & service-provider kind of relationship, the service provider provides the face of the service (as to what the service looks like) in the form of an interface.
One of the OOP concept is "Abstraction" which means to hide away complex working of the systems and show only what is necessary to understand the system. This helps in visualizing the working of a complex system.
This can be achieved through interfacewhere in each module is visualized (and also implemented) to work through interface of another module
它的
用途之一是将它用作服务的面孔。当两方一起工作形成服务-请求者和服务-提供者类型的关系时,服务提供者以接口的形式提供服务的外观(关于服务的外观)。
OOP 概念之一是“抽象”,这意味着隐藏系统的复杂工作,只显示理解系统所需的内容。这有助于可视化复杂系统的工作。这可以通过接口来实现,其中每个模块都可视化(并实现)以通过另一个模块的接口工作
回答by Premraj
In general, we prefer interfaces when there are two are more implementations we have. Where Interface is acts as protocol.
一般来说,当我们有两个更多的实现时,我们更喜欢接口。其中接口充当协议。
Coding to interface, not implementationsCoding to interface makes loosely couple.
编码到接口,而不是实现编码到接口使松散耦合。
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. for more details
接口是 Java 中的引用类型。它类似于类。它是抽象方法的集合。一个类实现了一个接口,从而继承了接口的抽象方法。除了抽象方法,接口还可以包含常量、默认方法、静态方法和嵌套类型。了解更多详情
回答by FREDDYSMALLZ
An interface is a class-like construct that contains only constants and abstract methods (Introduction to java programming, n.d.). Moreover, it can extend more than one interface for example a Superclass. Java allows only single inheritance for class extension but allows multiple extensions for interfaces(Introduction to Java programming, n.d.) For example,
接口是一种类结构,仅包含常量和抽象方法(Java 编程简介,nd)。此外,它可以扩展多个接口,例如超类。Java 只允许类扩展的单一继承,但允许接口的多个扩展(Java 编程简介,nd) 例如,
public class NewClass extends BaseClass
implements Interface1, ..., InterfaceN {
...
}
Secondly, interfaces can be used to specify the behavior of objects in a class. However, they cannot contain abstract methods. Also, an interface can inherit other interfaces using the extends keyword.
其次,接口可用于指定类中对象的行为。但是,它们不能包含抽象方法。此外,一个接口可以使用 extends 关键字继承其他接口。
public interface NewInterface extends Interface1, ... , InterfaceN {
}
Reference
参考
Introduction to Java Programming. Interfaces and Abstract classes (n.d). Retrieved March 10, 2017 from https://viewer.gcu.edu/7NNUKW
Java编程简介。接口和抽象类(nd)。2017 年 3 月 10 日从https://viewer.gcu.edu/7NNUKW检索
回答by Shashank Bodkhe
Interface is a contract. A simple exampleis a Tenantand Landlordwhich are the two partiesand the contractis the Rent Agreement. Rent Agreement contains various clause which Tenants have to follow. Likewise Interface is a contact which contains various method (Declaration) which the Party has to implement (provide method bodies).Here party one is the class which implement the interface and second party is Client and the way to use and interface is having “Reference of Interface” and “Object of Implementing class”: below are 3 components:(Explained with help of example)
接口是一种契约。一个简单的例子是租户和房东是双方,合同是租金协议。租金协议包含租户必须遵守的各种条款。同样,接口是一个联系人,其中包含各方必须实现的各种方法(声明)(提供方法体)。这里的一方是实现接口的类,第二方是客户端,使用方式和接口具有“参考”接口”和“实现类的对象”:下面是3个组件:(在示例的帮助下解释)
Component 1] Interface : The Contract
组件 1] 接口:合约
interface myInterface{
public void myMethod();
}
Component 2] Implementing Class : Party number 1
组件 2] 实施类:第 1 方
class myClass implements myInterface {
@Override
public void myMethod() {
System.out.println("in MyMethod");
}
}
Component 3] Client code : Party number 2
组件 3] 客户代码:第 2 方
Client.java
public class Client {
public static void main(String[] args) {
myInterface mi = new myClass();
// Reference of Interface = Object of Implementing Class
mi.myMethod(); // this will print in MyMethod
}
}
回答by Johnny
From the latest definition by Oracle, Interface is:
根据Oracle的最新定义,Interface 是:
There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.
The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.
[...] An interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
在软件工程中有很多情况,当不同的程序员群体同意一个阐明他们的软件如何交互的“合同”是很重要的。每个组都应该能够在不知道其他组的代码是如何编写的情况下编写他们的代码。一般来说,接口就是这样的契约。
例如,想象一个未来社会,计算机控制的机器人汽车在没有人工操作员的情况下在城市街道上运送乘客。汽车制造商编写软件(当然是 Java)来操作汽车——停止、启动、加速、左转等等。另一个工业集团,电子制导仪器制造商,制造接收 GPS(全球定位系统)位置数据和交通状况无线传输的计算机系统,并使用这些信息来驱动汽车。
汽车制造商必须发布一个行业标准接口,详细说明可以调用哪些方法来使汽车移动(任何汽车,来自任何制造商)。然后,指导制造商可以编写软件,调用界面中描述的方法来指挥汽车。两个工业集团都不需要知道另一个集团的软件是如何实现的。事实上,每个团体都认为其软件具有高度专有性,并保留随时对其进行修改的权利,只要它继续遵守已发布的界面即可。
[...] 接口是一种引用类型,类似于类,只能包含常量、方法签名、默认方法、静态方法和嵌套类型。方法体仅存在于默认方法和静态方法中。接口不能被实例化——它们只能由类实现或由其他接口扩展。
The most popular usage of interfaces is as APIs (Application Programming Interface) which are common in commercial software products. Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product.
接口最流行的用途是作为商业软件产品中常见的 API(应用程序编程接口)。通常,一家公司销售的软件包中包含另一家公司希望在自己的软件产品中使用的复杂方法。
An example could be a package of digital image processing methods that are sold to companies making end-user graphics programs.
例如,出售给制作最终用户图形程序的公司的数字图像处理方法包。
The image processing company writes its classes to implement an interface, which it makes public to its customers. The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. While the image processing company's API is made public (to its customers), its implementation of the API is kept as a closely guarded secret—in fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.
图像处理公司编写自己的类来实现一个接口,并将其公开给客户。然后图形公司使用接口中定义的签名和返回类型调用图像处理方法。虽然图像处理公司的 API 是公开的(向其客户),但它的 API 实现被严格保密——事实上,只要它继续实现原始接口,它可能会在以后修改实现它的客户一直依赖。
Check out to learn more about interfaces.
查看以了解有关接口的更多信息。
回答by Vishal Sheth
Interface : System requirement service.
接口:系统需求服务。
Description : Suppose a client needed some functionality "i.e. JDBC API" interface and some other server Apache , Jetty , WebServerthey all provide implements of this. So it bounded requirement document which service provider provided to the user who uses data-connection with these server Apache , Jetty , WebServer.
描述:假设一个客户端需要一些功能“即JDBC API”接口和一些其他服务器Apache,Jetty,WebServer,它们都提供了这个实现。因此它限定了服务提供商提供给使用这些服务器Apache 、 Jetty 、 WebServer数据连接的用户的需求文档。