Reputation: 20798
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
.objB
doSomething()
method has to do WorksA
, WorksB
and another extra called WorksBExtra
.That's all.
Upvotes: 3
Views: 100
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
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