开发者

Using composition

开发者 https://www.devze.com 2023-04-09 05:53 出处:网络
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

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! }
}


you are close, just do this with the Bar class

class Bar extends Foo {
   // note Bar is still of type SomeMethods because it extends a class of that type.
   public void doSomething() {
      super.doSomething();
      //add more code here if you want to do some more stuff, note you don't need to define this function if you don't need to do anything else.
   }
   public void doSomethingElse() {
      //don't call super, and do whatever you like
   }
}


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:

public void doSomethingElse() {
    .... // custom stuff
    foo.doSomethingElse(); // this is the equivalent of an inheritance super call, so it's optional
    .... // other custom stuff
}

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.

class Bar implements SomeMethod {
   private final SomeMethod foo;

   public Bar(SomeMethod foo) {
     this.foo = foo;  
   }

   public void doSomething() { foo.doSomething(); }
   public void doSomethingElse() { // do something else! }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号