Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have different return types for a overloaded method?

Tags:

overloading

In method overloading, is it possible to have different return types for a overloaded method? for example,

void foo(int x) ; int foo(int x,int y); double foo(String str); 

in general object oriented programming, is it possible?

like image 576
Dunith Dhanushka Avatar asked May 11 '10 03:05

Dunith Dhanushka


People also ask

Can overload have different return types?

An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type. When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass.

Why method overloading have different return types?

The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible.

Can we overload a method with different return type in CPP?

You cannot overload function declarations that differ only by return type. The function overloading is basically the compile time polymorphism. It checks the function signature.

Why is function overloading not possible with different return types?

Overloading is the mechanism of binding the method call with the method body dynamically based on the parameters passed to the method call. ... It is not possible to decide to execute which method based on the return type, therefore, overloading is not possible just by changing the return type of the method.


1 Answers

In a class, there can be several methods sharing the same name but differ in

  1. Parameter types
  2. Number of parameters
  3. Order of the parameters declared in the method

By depending on the parameters provided for the method, in the run time, compiler determines which version of the method to execute.

An overloaded method may or may not have different return types. But return type alone is not sufficient for the compiler to determine which method is to be executed at run time.

like image 197
Dunith Dhanushka Avatar answered Sep 29 '22 15:09

Dunith Dhanushka