Ijlal Hussain
Ijlal Hussain

Reputation: 490

Child class as a return type of parent class

In Test class Object is used with show method. If we write the Object with the show method of xyz class, so will it be wrong. I am confused here that Object is the parent class of all the classes. Can it be used any where.

class Test{
        Object show(){
        System.out.println("1");
        }
    }
    class xyz extends Test{
        String show(){
        System.out.println("2");
        }
    }


If i write the above code as

class Test{
        String show(){
        System.out.println("1");
        }
    }
    class xyz extends Test{
        Object show(){
        System.out.println("2");
        }
    }


If Object holds all classes or Object is the parent class of all classes so, does it matter where we use it?

Upvotes: 1

Views: 1919

Answers (1)

Fullstack Guy
Fullstack Guy

Reputation: 16908

As of Java 5, method overriding allows co-variant return types meaning the overriden method of the subclass can return a type which is more specific but still assignable to the parent method return type.

In this case since the parent method is returning Object the child method can in fact return a String which is a sub-class of Object and is assignable to it.

From the JLS specs:

Return types may vary among methods that override each other if the return types are reference types. The notion of return-type-substitutability supports covariant returns, that is, the specialization of the return type to a subtype.

If you try this with CharSequence in the parent class method and say an Integer in the child class method it won't compile:

class Test{
    CharSequence show(){
        System.out.println("1");
        return null;
    }
}
class xyz extends Test{
    Integer show(){  //won't compile
        System.out.println("2");
        return null;
    }
}

But replace the Integer with String it would compile as String implements / is a type of CharSequence :

class Test{
    CharSequence show(){
        System.out.println("1");
        return null;
    }
}
class xyz extends Test{
    String show(){
        System.out.println("2");
        return null;
    }
} 

Upvotes: 1

Related Questions