Java class A extends class B and overrides the method

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 an incomprehensible title. My question is: in class B, when I call foo () and I want the same operation as class A to have the value a. How can I achieve this and not duplicate the same code from A? If I omit foo () in class B, will this work? Or what happens when I call super.foo () in foo ();

+3
source share
4 answers

Since ClassY extends ClassX, you can remove private ClassY bfrom class B. Then you can simply set your instance of classX to an instance variable a. This allows you to foo()inherit 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;
    }
}
+4

, ClassX ClassY ( , , ). , foo() ?

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);
   }
}
+1

foo() B, , A. A, foo() B. foo() B, A, B, super.foo() ; , B, super.foo() foo().

+1

super.foo() .

0

All Articles