Java Programming - Declarations and Access Control - Discussion


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"); 

[A]. 0
[B]. 1
[C]. 2
[D]. Compilation fails.

Answer: Option D


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; 

Sudarshan Kumar said: (Mar 1, 2012)  
Otherwise declare a default constructor in the Super class.

This is because for calling super class constructor i.e the way that Object is always is our parent class.This is also another cause that compiler provide us default constructor.Compiler provide the default constructor like this .Let A is a class then constructor be like this

public A()

If you declare a constructor by your self then compiler insert a super(); as a first statement.

Sujana said: (Sep 7, 2012)  
Provide no-arg constructor in super class. A default, no-arg constructor is generated by the compiler only if the class has no constructor defined explicitly.

Praveen said: (Mar 26, 2013)  
Can constructor have return type?

Jilaba said: (Mar 30, 2013)  
No constructor have not any return type.

If it has return type the compiler does not considered as a constructor.

Mani said: (Jan 26, 2014)  
Can constructor have any arguments?

Ali said: (May 22, 2014)  
Yes, constructor have two types those are,
zero parameter constructor and parameterized constructor.

ex: public Sub(){}
public Sub(int a,int b){}

Overlord said: (Aug 1, 2014)  
We can't initialize an integer inside a class definition.

Viren said: (Jul 16, 2017)  
Thanks @Overlord.

Jeethu said: (Jan 28, 2022)  

Even if we don't do any initialization why do we get an error, I am not able to understand this problem. Please anyone explain it.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.