Declarations and Access Control

Q1: What will be the output of the program?
class Super
{ 
    public int i = 0; 

    public Super(String text) /* Line 4 */
    {
        i = 1; 
    } 
} 

class Sub extends Super
{
    public Sub(String text)
    {
        i = 2; 
    } 

    public static void main(String args[])
    {
        Sub sub = new Sub('Hello'); 
        System.out.println(sub.i); 
    } 
}

A Compilation fails.

B 0

C 2

D 1

ANS:A - 0

A default no-args constructor is not created because there is a constructor supplied that has an argument, line 4. Therefore the sub-class constructor must explicitly make a call to the super class constructor:

public Sub(String text)
{ 
    super(text); // this must be the first line constructor 
    i = 2; 
}



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.