3

Does such thing as dynamic inheritance exist in Java?

Just to clarify, by dynamic inheritance I mean: can I specify from what class I inherit certain class at runtime? (A inherits from { X | X ∈ {P, T, Q} })

I am just trying to understand what are my options if I need to implement, say, class Animal, which will have the following child classes: FlyingAnimal, WalkingAnimal, SwimmingAnimal, etc.

At the same time, I need to subdivide Animal into Humans and NonHumans, which will have slightly different behaviors. What I want to do is to derive Humans and NonHumans from Animal, and then derive Animal from Walkable, etc. - I want to decide which one it would be at the runtime (assuming that an animal can either walk, or fly).

3
  • 6
    Short answer: no. Long answer: noooooo. You cannot do this dynamically at runtime. Commented Apr 18, 2016 at 3:58
  • @LouisWasserman ha ha, good one :-) Commented Apr 18, 2016 at 4:02
  • You should implement all the classes you need. And select one at the runtime. Commented Apr 18, 2016 at 4:03

2 Answers 2

4

from what class I inherit certain class at runtime

No. Java is a compiled language with compile time type checking. However, it is possible to use a byte-code manipulation library like BCEL to create bytecodes at runtime; per the BCEL homepage one interesting application is the creation of classes from scratch at run-time

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

1 Comment

Thanks @Elliot! I'll take a look at it, although, I don't feel that my Java knowledge is sufficient to get into byte manipulation (at least, yet). But is there a way to inherit class X from one class (A), and then do something like casting of the result to the instance of a child class (B)?
3

The proper way or solving such situations usually is (de-) composition and delegation (these are the keywords to search for).

For example, your class could contain an object of these classes, and simply use it instead of inheriting.

i.e.

interface Engine {}
class Diesel implements Engine {}
class Electric implements Engine {}
class Car /* NOT extends Diesel/Electric */ {
  Enigne engine; /* delegate or composition pattern */
}

Comments

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.