I have an init method that is used and overridden through out an extensive heirarchy. Each init call however extends on the work that the previous did. So naturally, I would:
@Override public void init() {
super.init();
}
And naturally this would ensure that everything is called and instantiated. What I'm wondering is: Can I create a way to ensure that the super method was called? If all of the init's are not call, there is a break down in the obejct, so I want to throw an exception or an error if somebody forgets to call super
.
TYFT ~Aedon
Definition and Usage It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.
A polymorphic method is a method that can take many forms. By that that I mean, the method may at different times invoke different methods. Let's say you got a class Animal and a class Dog extends Animal and a class Cat extends Animal , and they all override the method sleep() Then.. animal.sleep();
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).
The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.
Rather than trying to do that -- I don't think it's achievable btw! -- how about a different approach:
abstract class Base {
public final void baseFunction() {
...
overridenFunction(); //call the function in your base class
...
}
public abstract void overridenFunction();
}
...
class Child extends Base {
public void overridenFunction() {...};
}
...
Base object = new Child();
object.baseFunction(); //this now calls your base class function and the overridenFunction in the child class!
Would that work for you?
Here's one way to raise an exception if a derived class fails to call up to the superclass:
public class Base {
private boolean called;
public Base() { // doesn't have to be the c'tor; works elsewhere as well
called = false;
init();
if (!called) {
// throw an exception
}
}
protected void init() {
called = true;
// other stuff
}
}
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