初始化接口? [英] Initializing an Interface?

查看:248
本文介绍了初始化接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的当前问题(将文件打印到Java中的物理打印机)我一直在运行代码,就像一个疯子试图从所使用的每个类的javadoc中吞噬任何有用的遗漏信息。

In a current problem I am having (printing a file to a physical printer in Java) I have been running through the code like a madman trying to devour any useful missed information from the javadoc of each class used.

现在,我从以前的问题中提取了相当多的代码,所以有一点我自己没有写。我注意到的问题是我抓到的代码是初始化一个对象,比如说是SimpleDoc,它实现了一个接口(Doc)并将它分配给那个接口?!

Now, I pulled quite a bit of this code from previous questions so there was a fair bit I didn't write myself. The issue I noticed is that the code I grabbed is initializing an object, say "SimpleDoc" which implements an interface (Doc) and assigning it to that interface?!

Little Code片段:

Little Code snippet:

Doc mydoc = new SimpleDoc(textStream, flavor, null);

现在,据我所知,我们在java中创建对象。我熟悉继承,我熟悉使用接口允许类继承多个超类的技巧。

Now as far as I was led to understand in java we create objects. I'm familiar with inheritance, and I'm familiar with the trick of using interfaces to allow a class to "inherit" multiple super classes.

但这并不是正确的。你可以创建一个实现接口的类,这对我很好。但是,当创建一个接口并将一个对象简化为其接口时,这里发生了什么?当我完全引用mydoc时我在访问什么?

But this just isn't sticking right. You can create a class which implements an interface, that is fine with me. But what is happening here when a interface is created and an object is reduced to its interface? What am I accessing when I reference mydoc exactly?

推荐答案

诀窍是要意识到你不是创造,实例化,或初始化接口。您只是将变量定义为您知道实现该接口的变量。

The trick is to realize that you're not "creating", "instantiating", or "initializing" an interface. You are simply defining a variable as being something that you know implements that interface.

您实际上是在告诉其他程序员正在使用此代码,对于此方法的其余部分,您只对 myDoc Doc 的事实感兴趣(即满足的东西Doc interface)。这可以使编程更简单,因为IDE的自动完成现在只显示由此接口定义的方法,而不是 SimpleDoc 能够执行的所有操作。

You are essentially telling other programmers working on this code that for the rest of this method, you are only interested in the fact that myDoc is a Doc (i.e., something that satisfies the Doc interface). This can make programming simpler because the IDE's auto-complete will now only show you the methods that are defined by this interface, rather than everything that a SimpleDoc is capable of doing.

想象一下,将来你想要扩展你的功能,以便根据一些输入你可以有不同的Doc实现。您可以说:

Imagine that in the future you want to expand your functionality so that you could have different implementations of Doc depending on some input. Rather than creating the SimpleDoc explicitly, you say:

Doc mydoc = docFactory.getByType(inputType);

docFactory 可以生成任何类型的 Doc ,这个方法并不关心实例化什么类型,因为它会像 Doc 一样对待它。

The docFactory can produce any type of Doc, and this method doesn't really care what kind gets instantiated, because it's going to treat it like a Doc regardless.

这篇关于初始化接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆