bsky
bsky

Reputation: 20242

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

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() {...}

Upvotes: 4

Views: 178

Answers (4)

scottb
scottb

Reputation: 10084

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.

Upvotes: 3

Agbalaya Rasaq
Agbalaya Rasaq

Reputation: 125

yeah, you overroad foo with foo(int a) , and gave it a new data type String , the compiler see this as a valid code but the other one Object foo() and String foo() is totally invalid in java

Upvotes: 1

Nir Levy
Nir Levy

Reputation: 12953

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.

Upvotes: 2

Dima
Dima

Reputation: 40510

Yes, and it does not even need to be a subclass foo(), and foo(int) are two completely different and unrelated functions as far as the compiler is concerned, each can have any return type you want.

Upvotes: 2

Related Questions