java 为什么我们需要接口而不是类以及我们从接口中实现了什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4745529/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:50:05  来源:igfitidea点击:

why we need interface instead of class and what we are achieving from interface

java

提问by Nishi

As we know that we can declare only the method signature and also can not create the instance of a Interface. then why we need interface. Unnecessary its loading into JVM. This is also one performance degradation. We are creating the interface and several classes implementing that interface and defining all the methods of the interface. Actually what we achieved from this interface. Could you please give me some example.

众所周知,我们只能声明方法签名,也不能创建接口的实例。那么为什么我们需要接口。不必要地将其加载到 JVM 中。这也是一种性能下降。我们正在创建接口和几个实现该接口的类并定义该接口的所有方法。实际上我们从这个接口实现了什么。你能给我举一些例子吗?

回答by Jigar Joshi

Interface is you are forcing your client to implement some specified thing, implementation will be remain to the client.Also java doesn't support multiple inheritance by extending multiple classes you can have multiple interface implemented.

接口是您强制您的客户端实现某些指定的东西,实现将保留给客户端。此外,java 不支持通过扩展多个类来实现多重继承,您可以实现多个接口。

For example : Listdeclares add(..)method all the implementation of List provides it implementations.

例如: List声明add(..)方法列表的所有实现都为其提供了实现。

Simpler would be.

会更简单。

You define an Interface Animaland a method speak()it means all Animal must will have to speak with different different implementation. Man will speak,Dog will bark,Lion will roar.

你定义了一个接口Animal和一个方法,speak()这意味着所有的 Animal 都必须用不同的实现来说话。人会说话,狗会吠,狮子会吼。

Why should we go for create class Animal extra. We can declare the speak() in every class. What is befit we will get from Animal class and implementing speak() in all the sub classes. Still I did not get this concept

为什么我们要额外创建类 Animal。我们可以在每个类中声明 speak()。我们将从 Animal 类中获得并在所有子类中实现 speak() 有什么好处。我仍然没有得到这个概念

Main advantage is inheritance and polymorphism [core concepts of OOP]

主要优点是继承和多态【OOP的核心概念】

You are specifyingAnimal's behavior here also.

您也在此处指定Animal 的行为。

You can have

你可以有

Animal obj = new Man();

Animal obj = getAnimalForThisCriteria(something here);//this will return some animal at runtime so you can catch instance using Animal.

You might have Three different Class Ma,Dog,Lion with same method but there is no way to tell they all are animal unless they extends or implements common class or interface, here comes the concept of structure

你可能有三个不同的类 Ma,Dog,Lion 使用相同的方法但是除非它们扩展或实现了公共类或接口,否则没有办法告诉它们都是动物,这里是结构的概念

回答by thkala

Having interfaces separate from classes allows for clearseparation between, well, the interface of an object and its implementation. Without them you would have no standard way to indicate that some class should not contain implementation details at all.

将接口与类分开允许清楚地分离对象的接口及其实现。没有它们,您将没有标准方法来指示某些类根本不应该包含实现细节。

Second, since Java does not support multiple inheritance, interfaces are a partial workaround, by allowing inheritance on the outward features of the class.

其次,由于 Java 不支持多重继承,接口是一种部分解决方法,允许继承类的外部特性。

回答by freespace

Interfaces are for when you care only about an object's capabilities, not how it achieves them.

接口适用于您只关心对象的功能,而不是它如何实现这些功能的情况。

Suppose you are writing the high level control code for a robot. You don't care about how the robot actually works, you only want to be able to tell it to go forward, backward, turn left or right, etc. Without interfaces, you would implement a abstract class called AbstractRobotthat has all methods as abstract methods. At this point you have basically created an interface,but in the form of an abstract class, but one that is 'heavier' than required.

假设您正在为机器人编写高级控制代码。你不关心机器人的实际工作方式,你只想告诉它前进、后退、左转或右转等。如果没有接口,你将实现一个名为的抽象类AbstractRobot,它的所有方法都是抽象的方法。在这一点上,您基本上已经创建了一个接口,但采用抽象类的形式,但比所需的“重”。

Lastly, a class can conform to multipleinterfaces, but can only inheritfrom one class. This allows some design patterns which rely on multiple inheritance.

最后,一个类可以符合多个接口,但只能从一个类继承。这允许一些依赖多重继承的设计模式。

回答by Trivikram

I'll try to explain this in simple words.

我将尝试用简单的语言来解释这一点。

Consider your favorite Computer Game, say Counter Strike. In this game, the players (terrorists or counter-terrorists) use weapons.

想想你最喜欢的电脑游戏,比如反恐精英。在这个游戏中,玩家(恐怖分子或反恐怖分子)使用武器。

If we teach the player how to use weapon(analogous to Interface), it can use any weapon like AK47, Maverick, Shotgun, Sniper(analogous to classes which inherit Weapon interface).

如果我们教玩家如何使用weapon(类似于接口),它可以使用任何武器,如AK47, Maverick, Shotgun, Sniper(类似于继承武器接口的类)。

The advantage of this is consider Bazooka(which implements Weapon) is developed in future versions. Then the current player will be able to use it without any modifications - as it knows how to use Weapon interface :-)

这样做的好处是考虑Bazooka(实现武器)是在未来版本中开发的。然后当前玩家无需任何修改就可以使用它 - 因为它知道如何使用武器界面:-)

This is just a simple example. There are many other reasons for using interfaces.

这只是一个简单的例子。使用接口还有许多其他原因。

回答by Maheshwar Reddy K

An analogy for an interface is to think of a class using an interface as being like an electric wall outlet, and think of the implementation as the plug. The outlet doesn't care what's behind the plug, as long as it fits in the outlet. In psuedocode terms it could be written like this:

接口的一个类比是将使用接口的类视为像墙上的电源插座,而将实现视为插头。插座不关心插头后面是什么,只要它适合插座。在伪代码术语中,它可以这样写:

public interface ElectricOutlet {
     public void powerUp(); 
}

And a class that implements ElectricOutlet might look like this:

实现 ElectricOutlet 的类可能如下所示:

public class Appliance implements ElectricOutlet {
    //member variables
    public void powerUp() {
        //Draw power from the wall
    }
    ...
}

So how do you use that interface? Like this:

那么如何使用该接口呢?像这样:

//lots of other code
ElectricOutlet out = new Appliance(); //plug the appliance into the outlet
out.powerUp; //power it up!

Of course, it doesn't have to be an appliance that you plug into an outlet. It could be a TV, or a laptop, or a lawn mower, but they all behave the same way from the outlet's point of view. So how does this apply to programming? In exactly the same way:

当然,它不一定是您插入插座的设备。它可以是电视、笔记本电脑或割草机,但从插座的角度来看,它们的行为方式都相同。那么这如何应用于编程呢?以完全相同的方式:

List<String> list = new ArrayList<String>(); // create a new List of Strings

I just created a new (empty) List of Strings. If it turns out that ArrayList doesn't provide the right performance, and LinkedList works better, I can go back and change that line to this:

我刚刚创建了一个新的(空的)字符串列表。如果事实证明 ArrayList 没有提供正确的性能,并且 LinkedList 效果更好,我可以返回并将该行更改为:

List<String> = new LinkedList<String>(); //should work better now

I can do this because both ArrayList and LinkedList implement the List interface, and thus they provide the same behavior (API), even though the internal implementations may be different. From the List's point of view, however, it doesn't matter what the internal workings are, just as long as the interface is there. This allows a lot of independence between classes, and allows more reuse.

我可以这样做是因为 ArrayList 和 LinkedList 都实现了 List 接口,因此它们提供了相同的行为 (API),即使内部实现可能不同。然而,从 List 的角度来看,内部工作方式无关紧要,只要接口在那里即可。这允许类之间有很多独立性,并允许更多的重用。

回答by Payilagam

Simple. I think Interfaces and Abstract classes are for the same purpose. The difference is If you extend an Abstract Class, you could not extend no other class in Java. Reason: Java does not support Multiple Inheritance. At the same time, You can implement any number of Interface for a class.

简单的。我认为接口和抽象类是为了同样的目的。不同之处在于,如果扩展抽象类,则不能扩展 Java 中的任何其他类。原因:Java 不支持多重继承。同时,您可以为一个类实现任意数量的接口。

回答by Sorter

The most important use of interfaces as i see it is passing code(anonymous inner classor lambda) to a method as parameter.

在我看来,接口最重要的用途是将代码(匿名内部类lambda)作为参数传递给方法。

Example:

例子:

Suppose we want to make a method which can return the execution time required to run a piece of code. We want to pass our code as a parameter to this method.

假设我们要创建一个方法,该方法可以返回运行一段代码所需的执行时间。我们想将我们的代码作为参数传递给这个方法。

interface Code{
     public void run();   
}


long getExectutionTime(Code code){

     long startTime = System.nanoTime();    
     code.run();    
     return System.nanoTime() - startTime;
}


getExecutionTime(new Code(){

     public void run(){
          //the code to be executed
     }
});

In java 8,

在 Java 8 中,

getExecutionTime(()->{ 
     //the code to be executed 
});

回答by umesh yadav

Interface is nothing but its a guide line for the new implementation it provides some instructions for new implementation and categorize the functionality of the object .In details like if we create an interface then we create an instruction for the implementation .

接口只不过是新实现的指导方针,它为新实现提供了一些说明,并对对象的功能进行了分类。详细地说,如果我们创建了一个接口,那么我们就为实现创建了一条指令。