dcp
dcp

Reputation: 55424

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?

Upvotes: 3

Views: 6038

Answers (4)

Thomas Langston
Thomas Langston

Reputation: 3735

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.oracle.com/sundararajan/entry/calling_overriden_superclass_method_on

Upvotes: 0

fredcrs
fredcrs

Reputation: 3621

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

Upvotes: 0

meriton
meriton

Reputation: 70564

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.

Upvotes: 0

BalusC
BalusC

Reputation: 1108537

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.

Upvotes: 12

Related Questions