Java Programming - Declarations and Access Control - Discussion

Discussion Forum : Declarations and Access Control - Finding the output (Q.No. 10)
10.
What will be the output of the program?
class Super 
{ 
    public Integer getLength() 
    {
        return new Integer(4); 
    } 
} 

public class Sub extends Super 
{ 
    public Long getLength() 
    {
        return new Long(5); 
    } 

    public static void main(String[] args) 
    { 
        Super sooper = new Super(); 
        Sub sub = new Sub(); 
        System.out.println( 
        sooper.getLength().toString() + "," + sub.getLength().toString() ); 
    } 
}
4, 4
4, 5
5, 4
Compilation fails.
Answer: Option
Explanation:

Option D is correct, compilation fails - The return type of getLength( ) in the super class is an object of reference type Integer and the return type in the sub class is an object of reference type Long. In other words, it is not an override because of the change in the return type and it is also not an overload because the argument list has not changed.

Discussion:
13 comments Page 2 of 2.

Pratik said:   10 years ago
Return type is does not matter in case of overriding.

Datla Kranthi said:   1 decade ago
class Super
{
public Integer getLength()
{
return new Integer(4);
}
}

public class Sub extends Super
{
public Integer getLength()
{
return new Integer(5);
}

public static void main(String[] args)
{
Super sooper = new Super();
Sub sub = new Sub();
System.out.println(
sooper.getLength().toString() + "," + sub.getLength().toString() );
}
}


Friends, if we keep Integer before getlength then we get result as 4,5.

Manjunath said:   1 decade ago
Your explanation is not exactly correct...Correct reason is,
2 methods getLength() can have same name, argument & also return type. but return type should be compatable. here return type Long in sub class is not compatable with Integer of super class.
so to compile change the 2 return types objects from super and sub.


Post your comments here:

Your comments will be displayed after verification.