Search code examples
javaoopparent

Overrides a method with all parents works in that method?


I have a class B, that extends from class A, class B overrides a class A's method:

public class ClassB extends ClassA {

    @Overrides
    protected void DoSomething() {
        super.DoSomething();
        // Some ClassB code here, called WorkB
    }
}

After that, I create a class B object, and I need do something extra in addition to what A's version in DoSomething():

ClassB objB = new ClassB() {

    @Overrides
    protected void DoSomething() {
        // I need to do something more here
    }

}

I need to know if I can do ALL of ClassA works, ClassB works, then add some other code for objB in this method? I have a solution: create a public method in ClassB, that do WorkB, then in objB, just call the method. But I want to know if there is/are another way (no matter worse or better my solution!).

EDIT: I will summarise the question so you can easily understand it:

  • Class A's doSomething method does something called WorksA.
  • Class B overrides doSomething, call super.doSomething() and some extra code, which mean it does WorksA and an extra called WorksB.
  • Object objB doSomething() method has to do WorksA, WorksB and another extra called WorksBExtra.

That's all.


Solution

  • Yes just call super.doSomething() first and it will throw up until Class A and then Class B. After that you can do specific stuff.

    public class A {
    public void doSomething() {
        System.out.println("A, ");
    }
    

    }

    public class B extends A {
    public void doSomething() {
        super.doSomething();
        System.out.println("B, ");
    }
    

    }

    public static void main(String[] args) {
        B b = new B() {
            @Override
            public void doSomething() {
                super.doSomething();
                System.out.println("new B");
            }
        };
        b.doSomething();
    }
    

    Outputs A, B, new B