简体   繁体   English

我可以在 java 8 中使用接口来继承属性吗?

[英]Can I use interfaces for inheritance of properties in java 8?

I have 4 classes : "stones", "seaweed", "sprats" and "pikes", each successive class inherits the properties of the previous one.我有 4 个类:“石头”、“海藻”、“鲱鱼”和“长矛”,每个连续的类都继承了前一个类的属性。

Class "stones" have the coordinates, a class "seaweed" added to the coordinates the lifetime and the rate of growth, as well as the birth of a new seaweed (division of old), in "sprats" added method of eating seaweed.类“石头”有坐标,类“海藻”在坐标上加了寿命和生长速度,以及新海藻的诞生(分裂老),在“鲱鱼”中加了吃海藻的方法。

Should I use normal java classes to express such inheritance or is there another way for such inheritance?我应该使用普通的java类来表达这种继承还是有另一种继承方式?

In such a case when semantically there is no real relation between the two objects I would discourage directly using class inheritance.在这种情况下,当语义上两个对象之间没有真正的关系时,我不鼓励直接使用类继承。

If you wish to express the fact that these classes have certain aspects of their behaviour in common, you might want to use interfaces which express these sets of properties.如果您希望表达这些类在其行为的某些方面具有共同点这一事实,您可能希望使用表达这些属性集的接口。 This works because a class can implement multiple interfaces, so you can pick and choose which to implement in each class.这是有效的,因为一个类可以实现多个接口,因此您可以选择在每个类中实现哪个。 This also introduces greater flexibility since a linear ordering of the different, not strictly related functionalities is not necessary.这也引入了更大的灵活性,因为不需要对不同的、不严格相关的功能进行线性排序。

Example: You could have例子:你可以有

public interface WorldObject {...}
public interface Organism extends WorldObject {...}
public interface Plant extends Organism {...}
public interface Animal extends Organism {...}
public interface Eater<T> {...}

public class Stone implements WorldObject {...}
public class Seaweed implements Plant {...}
public class Sprat implements Animal, Eater<Seaweed> {...}

etc.等等。

Composition is good alternative to inheritance.组合是很好的替代继承。

So you will have additional classes such as Coordinates , LifeStyle , Consumer所以你会有额外的类,比如Coordinates , LifeStyle , Consumer

and define your classes并定义你的类

class Stone{
Coordinates coordinates;
}

class Seaweed{
Coordinates coordinates;
LifeStyle lifestyle;
}

class Sprats{
Coordinates coordinates;
LifeStyle lifestyle;
List<Consumer<?>> consumers;
}

is it better alternative than inheritance, it depends on your project.它是否比继承更好的选择,这取决于您的项目。

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

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