I’m trying to use a custom class to override a method in its super class using composition.
Below is the code im trying, in the class “Bar” what object calls the method doSomethingElse() ? This is not my code and is linked to question – Using composition over inheritance when overriding
All of the instantiation is taking place within the child class.
class Child extents Parent(){
public Child(){
super();
addButtons():
}
addButtons(){
<custom code here>
}
}
class Parent(){
addButtons(){
add(button1);
}
}
interface SomeMethods {
void doSomething();
void doSomethingElse();
}
class Foo implements SomeMethod {
public void doSomething() { // implementation }
public void doSomethingElse() { // implementation }
}
class Bar implements SomeMethod {
private final Foo foo = new Foo();
public void doSomething() { foo.doSomething(); }
public void doSomethingElse() { // do something else! }
}
If your original point was to override doSomethingElse, then when using Composition instead, in Bar you would delegate all the other methods (in this case, doSomething) to Foo, and add your overridden behaviour in Bar.doSomethingElse()
So that could be something like:
Also (unrelated to the original question, but I can’t help mentioning it) to produce better code, you should inject the Foo dependency, not couple it to Bar.