English 中文(简体)
为什么你在 Java宣布一个接口,然后向它发出一个物体?
原标题:Why would you declare an Interface and then instantiate an object with it in Java?

一名朋友和我正在研究 Java。 我们今天正在研究接口,我们讨论了如何使用接口。

我的朋友们所举的例子包括:

IVehicle modeOfTransport1 = new Car();
IVehicle modeOfTransport2 = new Bike();

Where IVehicle is an interface that s implemented in both the car and bike classes. When defining a method that accepts IVehicle as a parameter you can use the interface methods, and when you run the code the above objects work as normal. However, this works perfectly fine when declaring the car and bike as you normally would like this:

Car modeOfTransport1 = new Car();
Bike modeOfTransport2 = new Bike();

因此,我的问题是——为什么在宣布和立即提出/em>目标时,你会使用前者的方法? 是否有必要?

最佳回答

确实如此。

确实需要在其他接口中操作的,则需在IVehicle操作。 如果它们接受参数和回归价值,则该守则更容易推广。

如你所指出的,其中任一物体均可被采用一种方法,接受四舍五入为参数。

如果你随后有使用特定行车或Bike的守则,那么宣布这些业务为Carly或Bike是有利的。 每一相关物体都可以使用卡车和贝凯特车,这两条都将是可操作的(即可以通过)。

问题回答

在宣布使用接口时,有一大加,即所谓的“连接接口”,而不是“与执行的关系”,这是一个大的OOD) 原则,这样,你就可以宣布这样的方法:

public void (IVehicle myVehicle)

and this will accept any object that implements that interface, then at runtime it will call the implementation like this:

public void (IVehicle myVehicle)
{
    myVehicle.run() //This calls the implementation for that particular vehicle.
}

回答原来的问题,为什么你会使用一个而不是另一个问题,有几个原因:

1) Declaring them using an interface, means you can later substitute that value with any other concrete class that implements that interface, instead of being locked into that particular concrete class

2) You can take full advantage of polymorphism by declaring them using an interface, because each implementation can call the correct method at runtime.

3) You follow the OOD principle of code to an interface

你真的问:我应该使用哪类参考?

总的来说,你希望尽可能使用一种参考类型,使你能够了解你需要的行为。 这意味着任何种类的界面或母体类别,而不是具体类型。 当然,不要这么说——例如,你当然不想把一切都宣布为<条码>。 反对:

2. 审议这些备选办法:

Set<String> values1 = new TreeSet<String>();
TreeSet<String> values2 = new TreeSet<String>();
SortedSet<String> values3 = new TreeSet<String>();

这三个方案都是有效的,但一般来说,第一种选择是<代码>数值1,因为只有你才能查阅<代码>的行为。 一套接口,因此,在另一个实施过程中,你可以很容易地交换:

Set<String> values1 = new HashSet<String>();

注意使用第二个选项<代码>数值2。 它允许你使用<代码>的具体行为。 树冠的执行方式,可在<条码>的不同实施过程中进行转换。 Set 变得更加困难。 只要达到你的目标,就将处以罚款。 因此,在你的例子中,使用<代码>Car或Bike。 只有当你需要查阅<代码>IVehicle接口以外的内容时,才参考。 知道以下工作不会奏效:

TreeSet<String> values2 = new HashSet<String>(); // does not compile!

Still there are times when you need access to the methods that are not in the most general type. This is illustrated in the third option values3 -- the reference is more specific than Set, which allows you to rely on the behavior of SortedSet later.

TreeSet<String> values3 = new ConcurrentSkipListSet<String>();

有关参考类型的问题不仅适用于已申报的变数,而且适用于必须具体说明每一参数类型的方法。 所幸的是,“作为尽可能一般的参考类别”规则也适用于方法参数。

Program to an interface rather than an implementation.

当你安排一个接口时,你将撰写能够处理任何类型车辆的代码。 因此,今后,你的法典应当不加修改地与培训和规划人员合作。

如果你忽视接口,那么你就会与化工和比克斯混杂在一起,任何新车辆都需要对编码作出进一步修改。

The principle behind this is:

开放延期,关闭至修改。

因为你没有真正地关注执行工作......只是它的行为。

你们有动物

interface Animal {
    String speak();
}

class Cat implements Animal {

    void claw(Furniture f) { /* code here */ }

    public String speak() { return "Meow!" }
}

class Dog implements Animal {

    void water(FireHydrant fh) { /* code here */ }

    public String speak() { return "Woof!"; }
}

现在,你想给你一pet。

Animal pet = new ...?
kid.give(pet);

你后来又回过来。

Animal pet = kid.getAnimal();

你们不想去。

pet.claw(favorateChair);

因为你不知道该肾脏是否有狗。 你们不关心。 你只知道——阿尼马尔斯——允许发言。 你们不知道他们与家具或消防水.的互动。 你们知道的是动物。 并且使你们的女儿处于边缘地位(不是!)

kid.react(pet.speak());

因此,当你做一次金鱼时, k的反响就很平坦(tur出金鱼不说!) 但是,当你 bear的时候,我们的反应是巨大的。

如果你说的话,你不会这样做。

Cat cat = new Cat();

因为你将生态限制在加油能力上。

很奇怪的是,你的论点是空洞的。 这里发生的情况是暗中转换为IVehicle。 你和你的朋友似乎正在争论一下它是否能够更好地立即这样做(根据第一部法律清单),还是后来(根据第二部法典,你称之为这种方法)。 不管怎么说,它会被暗中转换为IVehicle,因此真正的问题是——你是否需要处理一辆汽车,还是仅仅处理车辆? 如果你需要的是一台 IV,那么第一种方法是完全罚款(如果你想在稍后时刻透明地为双 bi开车,则更可取)。 如果你需要在你的法典中把汽车当作车子对待,那么就把它当作汽车。

Declaring interfaces and instantiating them with objects allows for a powerful concept called polymorphism.

List<IVehicle> list = new ArrayList<IVehicle>();
list.add(new Car());
list.add(new Bike());

for (int i = 0; i < list.size(); ++i)
    list.get(i).doSomeVehicleAction();   // declared in IVehicle and implemented differently in Car and Bike

明确回答问题: 您将使用接口声明(即使你知道具体类型),以便你能够将多种类型(采用相同的接口)传递给一种方法或收集;那么,无论实际类型如何,都可以援引每个执行类型的共同行为。

well interfaces are behaviors and classes are their implementation so there will be several occasions later when you will program where you will only know the behaviors(interface). and to make use of it you will implement them to get benefit out of it. it is basically used to hiding implementation details from user by only telling them the behavior(interface).

你的直觉是正确的;变量的类型应尽可能具体。

This is unlike method return types and parameter types; there API designers want to be a little abstract so the API can be more flexible.

变式不属APIC。 它们是执行细节。 摘要通常不适用。

Even in 2022, it s confusing to understand the true purpose of an interface even to a trained eye who didn t start his/her career in java.

After reading a lot of answers in various online posts, I think that an interface is just a way to not care about the implementation details of a certain activity which is being passed down to a common goal (a certain method). To make it easy, a method doesn t really care how you implement your operations but only cares about what you pass down to it.

The OP is correct in a way to ask why we couldn t just reference to the type of the concrete class than to use an interface. But, we cannot think or understand the use case of an interface in a isolated pov. Most explanation won t justify it s use unless you look at how classes like ArrayList and LinkedList are derived. Here is my simple explanation.

Class CustomerDelivery {

line 2 -> public void deliverMeMyIphone( DeliveryRoutes x //I don t care how you deliver it){
         //Just deliver to my home address.
    }
line 3 -> DeliveryRoutes a = new AmazonDelivery();
               DeliveryRoutes b = new EbayDelivery();
 
//sending IPhone using Amazon Delivery. Final act.
deliverMeMyIphone(a.route());
 
//sending IPhone using eBay Delivery. Final act
deliverMeMyIphone(b.route());
}

Interface DeliveryRoutes {

    void route(); // I dont care what route you take, and also the method which takes me as an argument won t care and that s the contract.

}
Class AmazonDelivery implements DeliveryRoutes {
   @overide route() {
           // Amazon guy takes a different route
     }
}

Class EbayDelivery implements DeliveryRoutes {
   @overide route() {
           // ebay guy takes a different route
     }
}

以上例子 第2行,只是想一想,如果你把价值x的类型投给亚马孙流域等具体类别,而不是交际交付类型,将会出现什么情况? 或者,如果你将接口类型从亚马孙肝类改变,第3行将会出现什么情况? 这将是一件大事。 为什么? 由于<代码>deliverMeMyIphone将被迫只使用一种交付方式,即亚马孙肝脏,并赢得任何接受。

多数答复使我们感到困惑,说话。 相互传承有助于真正的多重遗产,不会使我错过,但不是唯一的故事。

有了“IVehicle ModeOfTransport1 = 新的运输工具”;只有运输公司拥有的方法不能进入运输模式。 我不知道原因何在。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签