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 1 of 2.

Nikhil said:   4 years ago
In java, method overloading is not possible by changing the return type of the method only because of ambiguity.

Monika said:   4 years ago
@Nitin.

It is possible. But in this case method name same. So overloading is also not possible.

Nitin said:   5 years ago
Why its necessary to override super class method, can't we treat them different method and access it by class instance.

Gopi said:   7 years ago
Is Integer valid return type. I have used the only int all the time.

Khagendra said:   7 years ago
Overloading can't possible because it happens within a class, but overriding is happen in two different class in inheritance and here the two function name getLength () return different value. So, it is a contradiction of overriding concept, that's why the compile-time error occurs.
(1)

Khagendra said:   7 years ago
@Krishna.

Java is a case sensitive programming language.

Kkhushi said:   8 years ago
The super is reserved but not Super difference in capitals.

Krishna said:   8 years ago
Super is a reserved key word in java. How can we create a class by its name?

BhavyaSree said:   9 years ago
After Java5 version if base class method return type is nonprimitive we can change the return of overridden method in subclass this is called Covariant return type in java.

Farid said:   9 years ago
Answer [A].

Because overriding is not correct so when select getLength() it is select superclass method.


Post your comments here:

Your comments will be displayed after verification.