Java Programming - Declarations and Access Control - Discussion

Discussion Forum : Declarations and Access Control - Finding the output (Q.No. 4)
4.
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); 
    } 
}
0
1
2
Compilation fails.
Answer: Option
Explanation:

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; 
}
Discussion:
9 comments Page 1 of 1.

Jeethu said:   2 years ago
@Overlord.

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.

Viren said:   7 years ago
Thanks @Overlord.

Overlord said:   10 years ago
We can't initialize an integer inside a class definition.

Ali said:   10 years ago
Yes, constructor have two types those are,
zero parameter constructor and parameterized constructor.

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

Mani said:   1 decade ago
Can constructor have any arguments?

Jilaba said:   1 decade ago
No constructor have not any return type.

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

Praveen said:   1 decade ago
Can constructor have return type?

Sujana said:   1 decade ago
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.

Sudarshan Kumar said:   1 decade ago
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()
{
super();
}

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

Post your comments here:

Your comments will be displayed after verification.