简体   繁体   中英

How to implement multi inheritance in java with interfaces?

I need to mimic multi inheritance in Java. It might be wrong design but, since my problem is not with (parent) class functionality, I have not been able to mimic the feature with interfaces. Here is more description on the problem. I have a class called AbstractModel.java with number of methods. On the other hand, there is another class AbstractTableModel.java . Now assume that there is a class called table controller.java that deals with AbstractModel.java and on the other hand there is class called Tableview .java that deals with AbstractTableModel.java . I need have to some way to define : public class A extends AbstractModel , AbstracTableModel so that both view and controller can use the same class with extension. Please note that the solution AbstractTableModel.java extends AbstractModel is not a solution since it is a built-in java class.

Thank you.

You cannot do it directly in Java but you can use delegation design pattern . Look here . It is a very similar question on SO.

Change your code that expects an AbstractTableModel so that it accepts a TableModel instead (this is an interface implemented by AbstractTableModel ). This should be done anyway. Never depend on an concrete implementation when you can instead depend on an interface.

Then you can easily let class AbstractModel implement TableModel .

You should probably also think about creating an interface for AbstractModel . Usually one would create an interface X , an abstract base implementation AbstractX which provides common functionality shared by all implementations, and implementations MyX , YourX etc. Only the concrete implementations (but not necessarily all of them) would know and depend on AbstractX , but no code outside this hierarchy.

The Java Collections Framework is a good example of this: There is for example List , AbstractList , ArrayList and LinkedList , but there is no code that actually depends on an AbstractList . Most users of a list just use any List , or if they need a concrete implementation for some reason, they depend on that.

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