Waseem Saeed
Waseem Saeed

Reputation: 85

Can two overriding methods vary in return type in java?

class ab {   
    int add(int a, int b) {
        return a + b;
    }
}

class bc extends ab {
    String add(int a, int b) {
        return a + " " + b;
    }
}

If I am using JRE 5 will this code run? And what happens in JRE7 and JRE8?

Upvotes: 0

Views: 488

Answers (2)

Mathews Mathai
Mathews Mathai

Reputation: 1707

If you redefine a method with a different 'return' type in your sub-class,then it is not called over-riding unless the return type is similar(in your example one is string and the other is int-entirely different data types and so it is not over-riding).

Example: Super class:

    public class mysuper
{
    byte  newfun(int a)
    { 
       return 11;
     }
}

Sub class:

    public class mysub
{

    int newfun(int b)
    { // this is over-riding,the body of the function is different and the return type is different but similar
      return 12;
     }

}

Covering up:

1.In over-riding,the function return type is exactly the same or something similar,only the body could be different.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234875

You can only vary the return types if they are related (or covariant to use the strict term). Broadly speaking that means that one is reference-castable to the the other: i.e. one is a child class of another.

So no in your case since a String is not related to an int: an int is a primitive type.

Upvotes: 1

Related Questions