Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force a polymorphic call to the super method?

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

like image 466
ahodder Avatar asked May 26 '11 17:05

ahodder


People also ask

What does calling the super () method do?

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.

What is a polymorphic method call?

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();

Can you call a method from a superclass?

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).

Can we call super super method in Java?

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.


2 Answers

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?

like image 130
Liv Avatar answered Oct 22 '22 09:10

Liv


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
    }
}
like image 34
Ted Hopp Avatar answered Oct 22 '22 09:10

Ted Hopp