I have an abstract super class A with a method doSomething()
. A sub-class of A
must implement doSomething()
, but there is also some common code that should be called every time a subclass calls doSomething()
. I know this could be achieved thus:
public class A {
public void doSomething() {
// Things that every sub-class should do
}
}
public class B extends A {
public void doSomething() {
super.doSomething();
// Doing class-B-specific stuff here
...
}
}
There seem to be three issues with this, though:
Any ideas how the methods should be implemented?
Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).
Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.
Rule:A subclass inherits all of the member variables within its superclass that are accessible to that subclass (unless the member variable is hidden by the subclass). inherit those member variables declared with no access specifier as long as the subclass is in the same package as the superclass.
What about the following?
public abstract class A {
protected abstract void __doSomething();
public void doSomething() {
// Things that every sub-class should do
__doSomething();
}
}
public class B extends A {
protected void __doSomething() {
// Doing class-B-specific stuff here
...
}
}
The first bullet point however is not so clear. The signature can't match if you want to return something different.
add call back to doSomething()
public class A {
public void doSomething() {
// Things that every sub-class should do
doSomethingMore()
}
}
protected abstract void doSomethingMore()
so all subclusses will have to ipmelment doSomethingMore() with additional actions but external classes will call public doSomething()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With