Java - 抽象问题
我有这个烦恼。我正在使用一些库,我需要创建一个作为接口的类的实例。
- 如果我这样做
this.createITextArea()
它将创建该对象。 - 如果我这样做
ITextArea area = new ITextArea()
我不能,因为该类是抽象的。
事实上,我需要通过一个函数发送它。但使用第一种方法我不能,或者我不知道如何获取该类的变量。我怎样才能通过呢?
我需要诸如 area=this.createITextArea()
这样的东西,这样我就可以在函数中使用变量区域...
希望问题很清楚...
I have this trouble. Im working with some library, and i need to create an istance of a class that is an interface.
- If i do
this.createITextArea()
it will create the object. - If i do
ITextArea area = new ITextArea()
i can't, because the class is abstract.
In fact, i need to send it trought a function. But with first method i can't, or i don't know how to get the variable for that class. How can I pass it?
I need somethings like area=this.createITextArea()
, so i can use the variable area in the function...
Hope the question is clear...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那么这有什么问题:
?
So what's the problem with this:
?
尽管问题有点不清楚:
例如:
或内联:
我建议进一步阅读 Java 接口。
Despite the question being a bit unclear:
E.g.:
or inline:
I'd recommend further reading on Java Interfaces.
您不需要创建接口的实例。您需要创建一个实现所述接口的类的实例。查找或编写这样的实现,实例化它,然后将其分配给您的变量。
You do NOT need to create an instance of an interface. You need to create an instance of a class which implements said interface. Find or write such an implementation, instantiate that, and then assign it to your variable.
类的实例绝不是接口。方法可能返回接口类型,但是通过该方法获得的“事物”始终是实现该接口的对象。
一些简单的例子来说明它:
createList
方法返回一个接口类型(List
)但是它返回一个真实类的实例(>ArrayList
)。所以最后,局部变量list
保存了对此ArrayList
实例的引用。回到你的例子:假设你有一个接口
并且想要创建一个“实现这个接口”的对象,那么你需要另一个类似的类
,并且你需要创建这个具体类的实例。
An instance of a class is never an interface. A method may return an interface type, but the "thing", that you get through the method, is always an object which implements this interface.
Some simple examples to illustrate it:
The
createList
method returns an interface type (List
) but it returns an instance of a real class (ArrayList
). So at the end, the local variablelist
holds a reference to this instance ofArrayList
.Back to your example: Assuming you have an interface
and want to create an object "that implements this interface", then you need another class like
and you'll want to create instances of this concrete class.