a .s.
a .s.

Reputation: 79

if overridden method's return type is primitive (e.g. double) ,can we change return type of overriding method (e.g. int ,char)?

As shown below :

Method to be overriden:

double add (int a ,int b){  

} 

Method overridding above method:

int add(int a,int b){

}  

Upvotes: 3

Views: 3552

Answers (3)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78639

With primitive types it is not possible, but there is a feature added to JDK 1.5 called covariant return types. So, using this feature, a subclass could return a more specific type than the one declared on the parent class.

The following code compiles fine in JDK 1.7

public static class A {
   Number go() { return 0; };
}

public static class B extends A {
  @Override
  Integer go() { return 0; }
}

See JLS Example 8.4.8.3-1. Covariant Return Types

Upvotes: 8

keshlam
keshlam

Reputation: 8058

Another solution would be to make the base type a parameterized type, and assert the return type when you extend or instantiate it.

Upvotes: 1

Patrick J Abare II
Patrick J Abare II

Reputation: 1129

No, you cannot change the return type. You can overload a method by providing alternate or additional input.

i.e.

int add(int a, int b, int c)

Upvotes: 2

Related Questions