Suppose I have abstract class A and abstract class B which inherits from A, and I create an object of class A as shown:
abstract class A {
void func1();
}
abstract class B extends A {
void func2();
}
A objectA = new A() {
func1(){
//implementation
}
};
Is there a way for me to do something like this:
B objectB = new B(objectA) {
func2(){
//implementation
}
};
so that objectB gets the implementation of A’s functions from objectA?
I understand what you want to do. Such things are possible in Ruby for example. In Java it’s not possible that way because
is not of type
Abut an anonymous subclass ofAwhich is not a superclass ofB. The compiler generates some$1class for that.But in general try another approach: “Favor composition over inheritance”. Then are able to combine func1 and func2 somewhere just by using two Strategy classes. So if
Bis not using any state ofAyou could delegate toobjectA(which has to befinalthen):This is similar to bashflyng’s answer, but more direct.