0

Since I know Java doesn't support multiple inheritance, I'd like to know how could I implement this design in Java:

Class StudentModel extends BaseModel{
   public void doSomething(){};
}
Class ParentModel{
   protected List<BaseModel> children = new List<BaseModel>();
   public void addChild(BaseModel child){
      children.add(child);
   }
   // and other parent-children related functionality
}

Class ConcreteParentModel{
    // should contain both StudentModel and ParentModel functionalily
}

Thanks!

6
  • 1
    You can implement multiple interfaces, but only extend a single class. Commented Oct 29, 2015 at 20:19
  • You could use interfaces with (shudder) default methods. Commented Oct 29, 2015 at 20:19
  • 3
    You can always use composition instead of inheritance. Just make ConcreteParentModel have a parent and a student and have wrapper methods that pass the call to the appropriate instance variable. Commented Oct 29, 2015 at 20:20
  • What I aim to achieve is just less code. Implementing interfaces wouldn't do the job. I'll have to implement parent-related methods for every other class that also should be a "parent". Also a wrapper wouldn't do the job since i'll have to write the wrapper code for every derived class that should also be a parent. Commented Oct 29, 2015 at 20:31
  • 2
    If you want to write less code, use a language designed for that purpose - there are other languages on the JVM that may interest you. Java (the language) is designed for clean and robust code, not short code. Commented Oct 29, 2015 at 21:22

1 Answer 1

2

You should use an adapter pattern

In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used from another interface. It is often used to make existing classes work with others without modifying their source code.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but this would not help me to end with less code. I plan to add more other concrete classes that derive from other classes but all have this "parent" functionality.
Ok. I would implement a combination of adapters and strategy patterns then. In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.
I'm afraid this wouldn't help as well. I need all the inherited methods to be visible for Jackson via @JsonProperty
Unfortunately your only real solution is to use adapters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.