Luke Vo
Luke Vo

Reputation: 20798

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:

That's all.

Upvotes: 3

Views: 100

Answers (2)

Manuel Selva
Manuel Selva

Reputation: 19050

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

Upvotes: 4

Don Roby
Don Roby

Reputation: 41165

Your object is an instance of an anonymous subclass of ClassB, and you can override in exactly the same way:

ClassB objB = new ClassB() {

    @Override
    protected void DoSomething() {
        super.DoSomething();
        // do something more here just for this object.
    }

}

This code will first call the ClassB version of DoSomething(), which calls the ClassA version. So the net effect is to first do the ClassA stuff, then the ClassB stuff, then the stuff specific to the anonymous subclass.

I think you had the annotation wrong. It's @Override with no "s". Probably just a typo.

Also note that your DoSomething() is rather non-standard naming. You'd be better off calling it doSomething() in accordance with the way methods are usually named in Java.

Upvotes: 2

Related Questions