Friday, May 20, 2011

Published 5/20/2011 by with 2 comments

attempting to use incompatible return type

We may encounter this error message when we override a superclass method in the subclass with a wrong return type in the subclass method. To understand this, let's see the following two classes.

public class SuperClass
{
public double sum(double a,double b)
{
return (a+b);
}
}

public class Subclass extends SuperClass
{
public long sum(double a,double b)
{
return Math.round(a+b);
}
}

In the above example code, the super class method sum has double return type and in the subclass we have overridden this method where return type is long which is not compatible with double.
What should we do now to remove the error? We should either declare the return type of the subclass as double or change the parameter type.

See the correct code of the subclass below:

public class Subclass extends SuperClass
{
public double sum(double a,double b)
{
return Math.round(a+b);
}
public long sum(long a,long b)
{
return (a+b);
}
}


    email this       edit

2 comments:

  1. question: did you mean to round the sum of only the doubles, or also to get the result of the sum-method in long form to be rounded?

    the correct code could just as well have been:

    [Code]
    public class Subclass extends SuperClass{
    public long sum(long a, long b){
    return (a+b);
    }
    }
    [/Code]

    You may also want to add the label overloading, since that is what you are explaining here.

    ReplyDelete
  2. public static void convertToWave(int arr[], int n){

    // Your code here


    int temp;
    for(int i=0;i<n;i++)
    {
    if(arr[i] < arr[i + 1])
    {
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
    temp = arr[i];
    }
    }
    return arr;

    }

    }
    this show incompatible return type
    How tp remove such error ?

    ReplyDelete