Marthin
Marthin

Reputation: 6543

java correctness of override abstract method

Given the following:

public class RegistryIdModel extends AbstractTableModel{
     ContactExtensionProviderLocal provider;
     .
     .
     .
    @Override
    public ContactRegistryIdProviderLocal getProvider() {
        // TODO Auto-generated method stub
        return provider;
    }
}

public abstract class AbstractTableModel extends AbstractModel{
    public abstract MutableEntityProvider getProvider();
}

public interface ContactRegistryIdProviderLocal extends MutableEntityProvider<EppContactRegistryId>  {
....some methods....
}

Is it a good/bad solution to let the method in RegistryIdModel to Override the return type to a ContactRegistryProviderLocal?

If I do this, it makes my life easier but what might the effects be later on?

Tanks for any help or helpful comments! Marthin

Upvotes: 0

Views: 2467

Answers (4)

Kojotak
Kojotak

Reputation: 2070

You cannot override the return type. You can only provide (or specify) narrow implementation. This is called covariant return types (since Java 5). For example

abstract class A {
    abstract Serializable getId();
}

abstract class B extends A {
    @Override
    abstract Number getId();
}

class C extends B {

    @Override
    Integer getId() {
        return 42;
    }

}

Upvotes: 3

Cameron Skinner
Cameron Skinner

Reputation: 54276

Yes, overriding the return type to return a subclass is fine. You still fulfill the contract specified by AbstractTableModel.

Note that this will only work in Java 1.5 or above. Java 1.4 does not support covariant return types.

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95488

As long as the subtype that you're using complies with the specified interface, you should be ok. In this scenario, it would comply since you're extending the parent interface.

On another note, if all your specific implementations need to return specific types, I would question the need to include this method in your base (abstract) class.

Upvotes: 1

Alan Escreet
Alan Escreet

Reputation: 3549

ContactExtensionProviderLocal is-a MutableEntityProvider, so that means as long as it continues to function as a MutableEntityProvider in other parts of your system that don't know anything about a ContactExtensionProviderLocal, you've used OO principles well and you won't have any problems.

Upvotes: 3

Related Questions