3

How can I inherit from another class without adopting the parent type?

For example I want to be able to let Car adopt all methods and properties of Vehicle without being recognized as an Object of type Vehicle.

Is there a convenient way of doing this in Java without duplicating all methods and properties?

Daniel
  • 3,541
  • 3
  • 33
  • 46
  • Maybe I didn't understand the question but you might want to define the `interface Vehicle` and let `Car` implement that interface. – Robert Kock Sep 25 '18 at 09:35
  • 5
    So, you want delegation instead of inheritance. Java does not have a convenient way to implement delegation. – Jesper Sep 25 '18 at 09:35
  • you can extract the methods of vehicle to an interface that will be used by vehicle and by car. Then your car does not have to be a vehicle – vmrvictor Sep 25 '18 at 09:39

5 Answers5

6

It depends on your definition of convenient. You are a looking for Forwarding/Composition/Aggregation, essentially:

class B {
  A a;
  T foo() { return a.foo(); }
}

Which implies that all methods defined in A need to be duplicated in B.

This often comes up in discussion about Inheritance vs. Aggregation.

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
3

I think what you want to do is use the delegate pattern there is no easy way to do this with native Java, you could use the project Lombok Delegate to make it really convenient.

Matthieu Gabin
  • 830
  • 9
  • 26
2

If Car and Vehicle inherit from a common patent, they will have the same methods without Car being a Vehicle and no duplication.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

it's very hard you have to use bytecode reverse endangering library like javassist. here some example of using javassist to manipulate java class file

http://www.javassist.org/tutorial/tutorial2.html#intro

0

If you are using Spring Framework, you can define abstract bean for that purpose https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-child-bean-definitions

Nhan D Le
  • 129
  • 1
  • 4