Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a method be overloaded with another which returns a subclass?

Tags:

java

I know that a method can be overriden with one that returns a subclass.

Can it also be overloaded by a method which returns a subclass?

public Object foo() {...}
public String foo(int a) {...}

Is the above code valid?(if placed within a Class)

What about?

public Object foo() {...}
public String foo() {...}
like image 711
octavian Avatar asked Feb 08 '23 04:02

octavian


2 Answers

Beginning with Java 5, covariant return types are allowed for overridden methods. This means that an overridden method in a subclass is allowed to use a signature which returns a type that may be a subclass of the parent signature's return type.

To make this concrete, say you have this interface:

public interface MyInterface {
    Number apply(double op1, double op2);
      :
      :
}

The following is legal because the return type is a subclass of Number:

public class MyClass implements MyInterface {
    :
    :
    @Override
    public Integer apply(double op1, double op2) {
        :
        :
        return Integer.valueOf(result);
    }
}

Because overloaded methods (which have the same name but different signatures) are effectively different methods, you are free to use different return types if you like ... however ... this is discouraged because methods that have the same name but different return types can be confusing to programmers and can complicate the use of your API. It's best not to overload mrthods when you can reasonably avoid it.

like image 169
scottb Avatar answered Feb 10 '23 20:02

scottb


This example:

public Object foo() {...}
public String foo(int a) {...}

as long as the two methods get different set of variables, there's no problem with returning different types (even if they are not subclass).

The logic is very simple - if the compiler can choose without doubt which one to use - there's no issue. In this case- if you give the method int it's one method, and without parameters it's the other, no dilema (and the same name does not matter here)

as for:

public Object foo() {...}
public String foo() {...}

This one is not valid, since here the compiler can't 'choose' which one to use.

like image 32
Nir Levy Avatar answered Feb 10 '23 20:02

Nir Levy