可能接口拥有一个已经实例化的对象作为属性吗?

huangapple go评论83阅读模式
英文:

is it possible for an interface to have an already instanced object as an attribute?

问题

我正在创建一个带有许多实现类的接口,它们都必须具有一个属性;
我想最好是将该属性放在它们的接口中,而不是编写许多构造函数行,但属性只能是静态 final 的,并且需要立即初始化。

public interface Interface{

     static final AttrType attribute = new AttrType( *something* ); 

我有两个问题:这个属性是一个类,它的构造函数需要一些其他类型的参数,而不仅仅是整数;而且它不应该在这里初始化,我需要接口的所有实现类都在同一个 AttrType 实例上操作,正如我所说,我不会在接口中实例化它。

所以,因为我不是足够专业,是否有办法在接口中实现这一点,或者我应该在每个子类的构造函数中写一行代码,将它放入它们所需的那个 AttrType 实例中?

英文:

I am creating an interface with many implementing classes and there is an attribute they must all have;
I guess it's better to put that attribute in their interface than writing many constructor lines, but attributes can only be static final and require to be immediately initialized.

public interface Interface{

     static final AttrType attribute = new AttrType( *something* ); 

I have 2 problems: this attribute is a class and its constructor needs some other type parameters not just ints, and also it shouldn't be initialized here, I need all implementing classes of the interface to work on the same instance of AttrType which as i said I won't instantiate in the interface.

So, as I am not expert enough, is there a way to do this in the interface or I should just write a line in every subclass' constructor to put in the one AttrType instance they need?

答案1

得分: 0

可以给你的通用接口添加一个共同的基类,使得所有类都可以继承它?然后,这个共同的基类构造函数可以包含属性实例。另外,你也可以考虑使用抽象类来替代接口。

英文:

Would it be possible to add also a common base class to go with your common interface which all the classes could inherit? Then the common base class constructor could contain the attribute instance. Also you could consider using an abstract class instead of interface.

答案2

得分: 0

Java接口描述了一个类能做什么,而不是一个类是什么。因此,接口只描述了方法。

你可以用几种方式来处理这个问题:

使用接口,你可以为变量创建一个getter方法,这将强制实现这个接口的类拥有这个变量。类似于 "public AttrType getAttribute();"。

或者你可以创建一个类,可能是抽象类,它实现了接口并拥有这个变量,以及它的getter和setter方法。所有的子类都将继承这个变量和行为。

英文:

Java interfaces describe what a class can do, rather than what a class is. Therefore, an interface only describes methods.

You could handle this in a few ways:

Using an interface, you could have a getter for the variable, which would force the implementing classes to have the variable. Something like "public AttrType getAttribute();"

Or you could create a class, probably abstract, which implements the interface and has the variable, and its getter and setter. The subclasses all would inherit this variable and behavior.

huangapple
  • 本文由 发表于 2020年4月5日 16:42:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/61040044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定