views:

105

answers:

4

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?

+6  A: 

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.

BalusC
Thanks, it's not my design, I'm just coding it :).
dcp
You're welcome. I see, good luck with coding :)
BalusC
then question the quality of the design - i.e. tell the designer that he sucks ;)
Bozho
@Bozho - LOL, probably not the best way to make friends :). Thanks for the laugh though :).
dcp
@dcp, sure, don't tell him directly. But discuss a potential change.
Bozho
A: 

You can, but only in the subclass:

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

If you don't want overriding, why not name the method differently? If callers must be able to choose the method they invoke, the methods do different things, which should be reflected in the method name.

meriton
A: 

If you cast, it will still use the override method. So you should do something like that...

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

Then you call validatesSuper, it should work, bot is far from good OO programming, and I really do not recommend you to do that; If you need to call a different validate so you should just give a different name for that method and call it when you need, or call validate to invoke the superclass method now, not overrided, like this...

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

you will still can call validade from superclass

fredcrs
A: 

There is no way to do that in Java, except from within the subclass with super.methodName(). Not even with reflection. Other languages such as Ruby can do it with reflection.

http://blogs.sun.com/sundararajan/entry/calling_overriden_superclass_method_on

Thomas Langston