Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java class A extends class B, and method override

public class A {
   protected ClassX a;
   public void foo() {
       operations on a;
   }
}

public class B extends A {
   private ClassY b; // ClassY extends ClassX
   @Override
   public void foo() {
       //wanna the exact same operation as A.foo(), but on b;
   } 
}

Sorry for such a not clear title. My question is: in class B, when I call foo(), and I want the exact same operation as class A have on a. How do I achive that and without duplicate the same code from A? If i leave out foo() in class B, would it work? Or whats happening when I call super.foo() in foo();

like image 895
xiaofan2406 Avatar asked Dec 31 '25 23:12

xiaofan2406


2 Answers

Since ClassY extends ClassX, then you can remove private ClassY b from class B. Then you can just set your instance of ClassX to the a instance variable. This allows foo() to be inherited in class B, but still use the same logic and instance variable.

public class A {
    protected ClassX a

    public void foo() {
        // operations on a;
    }
}

public class B extends A {
    // do something to set an instance of ClassY to a; for example...
    public void setClassY(ClassY b){
        this.a = b;
    }
}
like image 107
Jeremy Avatar answered Jan 03 '26 13:01

Jeremy


It sounds like ClassX and ClassY would have a common interface (if they have the same methods you want to call on earch, at least). Have you considered making foo() take in an object of the type of the common interface?

public class A {
   private ClassX a;
   protected void foo(ClassXAndClassYInheritMe anObject) {
       operations on anObject;
   }

   public void foo() {
       foo(a);
   }
}

public class B {
   private ClassY b;
   @Override
   public void foo() {
       foo(b);
   }
}
like image 30
nicholas.hauschild Avatar answered Jan 03 '26 13:01

nicholas.hauschild



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!