简体   繁体   中英

Inherit class without parent type in Java

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?

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 .

我认为你想要做的是使用委托模式没有简单的方法来使用本机Java,你可以使用项目Lombok Delegate使它非常方便。

如果汽车和车辆继承了共同的专利,他们将采用相同的方法,而不是汽车是车辆而且没有重复。

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

如果您使用的是Spring Framework,则可以为此目的定义抽象bean https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-child-bean-definitions

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