Please let me know if this is possible in Java?
It's impossible. You cannot dynamically combine behavior in Java.
The usual way to combine behavior in Java is to use some combination of inheritance, wrapping, or delegation. Even then there will be a problem of subtyping ... if you are not using interfaces ... because Java does not allow a class to have multiple (direct) superclasses.
Consider the @Panzercrisis example. While the test03 class implements methods with the same signatures as the test01 and test02 classes, the test01 instance test03 not compatible with any of them. (You cannot use an instance of test03 as test01 or test02 . Java does not support duck printing!)
To solve the problem, you need to define the face01 and face02 , which are implemented by test01 and test02 . Then you implement test03 as implementing both face01 and face02 .
But these are all static classes and static typing.
In some cases, you can use DynamicProxy or something similar to “synthesize” a class that “combines” the behavior of two existing classes. However, all this is done using static types and code generation behind the scenes. Moreover, this approach would be viable if you had the prudence to define a bunch of interfaces (for example, face01 and face02 ) and write application code for interfaces, not implementation classes.
Stephen c
source share