简体   繁体   中英

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.

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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