简体   繁体   English

Java中的接口如何工作?

[英]How does an Interface in Java work?

I'm self learning Java, and I'm stuck on a chapter about Interfaces. 我是自学Java,而且我一直在关于接口的章节。 I simply cannot understand how they work in Java. 我根本无法理解它们在Java中是如何工作的。

I believe I understand perfectly what Interface means and how they apply in everyday situations and technology. 我相信我完全理解界面的含义以及它们在日常情况和技术中的应用方式。

But when it comes to Java, code-wise and logic-wise, I'm stuck. 但是当涉及到Java,代码方面和逻辑方面时,我陷入困境。 I don't get it. 我不明白。 How does the concept work? 这个概念是如何运作的?

Say I have 3 objects, and 1 interface object. 假设我有3个对象和1个接口对象。 2 Objects are ObjectCalculatingA, ObjectCalculatingB, ObjectMathFunctions, and ObjectInterface. 2对象是ObjectCalculatingA,ObjectCalculatingB,ObjectMathFunctions和ObjectInterface。

Supposedly in ObjectInterface there must be some sort of reference to the ObjectMathFunctions, so that ObjectCalculatingA and B can just access the math functions in ObjectMathFunctions without writting them all again in A and B. 据说在ObjectInterface中必须有一些对ObjectMathFunctions的引用,因此ObjectCalculatingA和B只能访问ObjectMathFunctions中的数学函数而无需在A和B中再次写入它们。

Am I right? 我对吗?

An interface exists to facilitate polymorphism . 存在促进多态性的接口。 It allows declaring a contract that any class that implements the interface must honor. 它允许声明一个实现接口的任何类必须遵守的合同。 And so it is a way to achieve abstraction and model complexity by looking for commonality between things . 因此,它是通过寻找事物之间共性来实现抽象和模型复杂性的一种方式。

An example? 一个例子? How about shapes? 形状怎么样? All shapes have an area, right? 所有形状都有一个区域,对吗? So you could have the following classes: 所以你可以拥有以下课程:

  • Square 广场
  • Circle

Then let's say you have another class that allows you to collect shapes, and return the total area: 那么假设你有另一个类,它允许你收集形状,并返回总面积:

for (Shape shape in shapes)
{
    area += shape.area()  //This is polymorphism
}

In the example above, we don't care whether the shape is a square or a circle. 在上面的示例中,我们不关心形状是正方形还是圆形。 We can accept either. 我们也可以接受。 We only care that it implements the Shape interface. 我们只关心它实现了Shape接口。 Each object will provide their own custom implementation of area - these internal details aren't important, only that it honors the area contract . 每个对象都将提供自己的自定义区域实现 - 这些内部细节并不重要,只是它尊重区域合同 See now how we're managing complexity? 现在看看我们如何管理复杂性? We can use the class without having to worry about all of the things that go on inside. 我们可以使用该课程,而不必担心内部发生的所有事情。 At this point what it does is important to us, not how it does it, which lets us focus on the problem at hand not getting distracted by complex details. 在这一点上它对我们来说很重要,而不是它如何做到这一点,这让我们专注于手头的问题而不会被复杂的细节分散注意力。

This polymorphism is one of the reasons why object oriented programming was considered such a powerful evolutionary step in programming. 这种多态性是面向对象编程被认为是编程中如此强大的进化步骤的原因之一。 The other key foundation concepts in Object Oriented Programming are: 面向对象编程中的其他关键基础概念是:

. . . you'll also need to learn these. 你还需要学习这些。

Abstract Base Class vs Interface 抽象基类与接口

As a comment said, another way to achieve polymorphism is to use an Abstract Base Class. 正如评论所说,实现多态的另一种方法是使用抽象基类。 Which should you choose? 你应该选择哪个?

  • Use an interface class implementing it will have its own hierarchy and dependencies. 使用实现它的接口类将具有自己的层次结构和依赖项。 For example a media player. 例如媒体播放器。 A Movie Player and a Sound Player might have totally different base classes, so use an interface. 电影播放器​​和声音播放器可能具有完全不同的基类,因此请使用界面。

  • Use an Abstract base class when you have some commonality between things, but the specifics vary. 当事物之间存在某些共性时,请使用Abstract基类,但具体情况会有所不同。 For example a message parsing framework. 例如,消息解析框架。

In simple lay mans language. 在简单的平铺语言中。 Interface is a contract and classes implementing the interface need to adhere to the contract. 接口是一个契约,实现接口的类需要遵守合同。 There can be many implementations for same interface and users can select which implementation they wish to use. 可以有许多相同接口的实现,用户可以选择他们希望使用的实现。 For more detailed information I suggest you read book like HeadFirst JAVA. 有关更多详细信息,我建议您阅读像HeadFirst JAVA这样的书。

Once you begin software development you will understand that many a times you would come across an already implemented piece of code which you feel is not properly implemented. 一旦开始软件开发,您就会明白,很多时候您会遇到一段已经实现的代码,您认为这些代码没有得到正确实现。 But at the same time a colleague of yours feels its correctly implemented and serves his purpose. 但与此同时,你的一位同事认为它正确实施并符合他的目的。 This is where interfaces come into play. 这是接口发挥作用的地方。 Your colleague who feels this implementation works for him can continue using the current one whereas you can implement your new implementation but you need to make sure that it adheres to the interface so that in future if your implementation is better, your colleague will have an oion to switch over. 您认为此实施适用于他的同事可以继续使用当前的实施,而您可以实施新的实施,但您需要确保它遵守界面,以便将来如果您的实施更好,您的同事将有一个oion切换。

List<String> myList = new ArrayList<String>();

In above example arraylist is on of the implementations of the List interface. 在上面的示例中,arraylist是List接口的实现。 Consider this example, ArrayList is not suiting your requirments so you can do the following. 考虑这个例子,ArrayList不符合您的要求,因此您可以执行以下操作。

myList = new LinkedList<String>();

This is the power of 'Coding to interface' 这是'编码接口'的力量

From your example, it shows that you lack a basic understanding of Object-Oriented Programming. 从您的示例中可以看出,您对面向对象编程缺乏基本的了解。 You are trying to learn how to run without having learned to stand up yet. 你正试图学习如何在没有学会站起来的情况下跑步。

In your example, you assume there is a class ObjectMathFunctions . 在您的示例中,您假设有一个ObjectMathFunctions类。 This is not Object-oriented at all, classes should model a real concept. 这根本不是面向对象的,类应该建立一个真实的概念。

1. Learn about objects / classes 1.了解对象/类

You should first learn how classes and objects work. 您应该首先了解类和对象的工作原理。 A class is not just any arbitrary division of code, it models something real. 一个类不仅仅是任意的代码划分,它模拟真实的东西。 Examples: Car, Wheel, etc. 示例:汽车,车轮等

2. Learn about inheritance 2.了解继承

After you understand that, learn about inheritance: a Car has a getWeight() method. 了解之后,了解继承:Car有一个getWeight()方法。 A Wheel has a getWeight() method as well. Wheel也有一个getWeight()方法。 Hmm, maybe they are both subdivisions of a broader concept: PhysicalThings. 嗯,也许它们都是更广泛概念的细分:PhysicalThings。 Every PhysicalThing has a getWeight() method. 每个PhysicalThing都有一个getWeight()方法。

After this, learn about overriding methods in subclasses, learn about abstract classes, etc. 在此之后,了解子类中的重写方法,了解抽象类等。

3. Learn about interfaces 3.了解接口

Now you will understand that an interface is very similar to an abstract class. 现在您将了解interface与抽象类非常相似。 You will have done some exercises where you already encountered the problem "This is a PhysicalThing , but it is also CanExplode (eg wheel of car, dynamite, etc). This single inheritance model is annoying, how do I fix this?". 你已经做过一些练习,你已经遇到过这个问题“这是一个PhysicalThing ,但它也是CanExplode (例如汽车轮,炸药等)。这个单继承模型很烦人,我该怎么解决这个问题?”。

If you know that a class can consist of both data and the functions that operate on the data, then an interface is just a list of the functions that a class has to implement. 如果您知道一个类可以包含数据和对数据进行操作的函数,那么接口只是一个类必须实现的函数列表。

Take a light switch interface, ILightSwitch ... 拿一个电灯开关接口,ILightSwitch ......

public interface ILightSwitch {
    void turnOn();
    void turnOff();
}

A class implements an interface if it implements those functions above. 如果一个类实现了上面的那些函数,它就实现了一个接

eg A LightSwitch class might be 例如,LightSwitch类可能是

public class LightSwitch implements ILightSwitch {
    boolean on = false;
    void turnOn() { on = true; }
    void turnOff() { on = false; }
}

The LightSwitch class implements the ILightSwitch interface. LightSwitch类实现 ILightSwitch接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM