Given an class hierarchy:
A -> B -> C -> instanceOfC
is it possible (and how) to insert a class, temporarily, at runtime, like so:
A -> B -> B' -> C -> instanceOfC?
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
Because Java is statically typed at compile time you get certain guarantees from the compiler but you are forced to follow rules in exchange or the code won't compile. Here, the relevant guarantee is that every instance of a subtype (e.g. Child ) can be used as an instance of its supertype (e.g. Parent ).
To inherit from a class, use the extends keyword.
It's possible if you use AspectJ. AspectJ has a declare parents
statement that enables you to do exactly that, and through Load Time Weaving you should be able to do it at runtime, also. However, you will not be able to do it on already loaded classes (at least not easily, maybe it works if you unload the class first).
Reference:
But methinks you are trying to solve the wrong problem here. I'd say try to replace inheritance with aggregation, let C
have a member of type D
to which functionality is delegated and just pass in a different implementation of D
. That's called the strategy pattern, and it's a much cleaner way to do things (and it's testable too)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With