Search code examples
javaoverridingabstract-class

What does it mean "return a type that is compatible"?


I am newby to Java, so I am reading Java Head First. I have seen that when you have an abstract class with abstract methods, you should override these abstract methods in a concrete class which means "create a non-abstract method in your class with the same method signature (name and arguments) and a return type that is compatible with the declared return type of the abstract method."

I can clearly understand the first part about having the same signature (name and arguments), but I would like to have a clear explanation about a return type that is compatible with the declared return type of the abstract method.

What exactly means a compatible type? Could somebody please provide an example? Is it like the return type should be the class or a subclass of the return type defined in the abstract method?


Solution

  • Consider the example below. The return type of the abstract function model() is int.

    abstract class Bike{  
      abstract short model();  
    }  
    
    • When you redefine this method in a concrete class which extends the abstract class Bike. The concrete class should have a method model() with the same method signature and a compatible return type.

    One return type is compatible with another, if it doesn't lead to loss of precision.

    One return type compatible with short is int.

    class Honda4 extends Bike{  
        int model() 
        //long is compatible with int since there is no loss of precision
        {
             return 1234;
        }  
    
        public static void main(String args[]){  
            Bike obj = new Honda4();  
            System.out.println(obj.model());  
        }  
    
    }  
    

    Can you name a return type which is not compatible with int ?

    • short. It may lead to loss of precision.