Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call base class method?

Say I have classes declared like this:

public abstract class IdentifiableEntity  {
    public boolean validate() {
        return true;
    }
}

public class PreferenceCategory extends IdentifiableEntity {
    public boolean validate() {
        return true;
    }
}

Now, let's say I have PreferenceCategory variable created, and I want to call the IdentifiableEntity.validate() method, not the PreferenceCategory.validate() method.

I would have thought I could do this with a cast (see below), but it still calls the overridden method:

PreferenceCategory cat = new PreferenceCategory();

// this calls PreferenceCategory.validate(), not what I want
((IdentifiableEntity)cat).validate(); 

Is there any way to do it?

like image 259
dcp Avatar asked Feb 14 '26 05:02

dcp


1 Answers

You can't. Your best bet is to add another method to PreferenceCategory which calls super's validate() method.

public boolean validateSuper() {
    return super.validate();
}

But why would you like to do that? This is a bit a design smell. You may find the chain of responsibilty pattern interesting.

like image 67
BalusC Avatar answered Feb 16 '26 17:02

BalusC