Java Programming - Declarations and Access Control - Discussion

Discussion Forum : Declarations and Access Control - Finding the output (Q.No. 7)
7.
What will be the output of the program?
class Base
{ 
    Base()
    {
        System.out.print("Base");
    }
} 
public class Alpha extends Base
{ 
    public static void main(String[] args)
    { 
        new Alpha(); /* Line 12 */
        new Base(); /* Line 13 */
    } 
}
Base
BaseBase
Compilation fails
The code runs with no output
Answer: Option
Explanation:

Option B is correct. It would be correct if the code had compiled, and the subclass Alpha had been saved in its own file. In this case Java supplies an implicit call from the sub-class constructor to the no-args constructor of the super-class therefore line 12 causes Base to be output. Line 13 also causes Base to be output.

Option A is wrong. It would be correct if either the main class or the subclass had not been instantiated.

Option C is wrong. The code compiles.

Option D is wrong. There is output.

Discussion:
5 comments Page 1 of 1.

Serg said:   4 years ago
It would be correct if the code had compiled. But the code would not compile. So, Compilation fails.

Mani said:   7 years ago
Very useful, Thanks.

SupremeWa said:   1 decade ago
When you first call new Alpha(), you call the default constructor of Alpha. Since it is not explicitly declared, it is implicitly defined as :

public Alpha() {
super();
}

Therefore, new Alpha() calls the default constructor of Base (Becauses Alpha is a subclass of Base), which prints "Base". Then, new Base() also calls that constructor and prints again "Base", resulting in a final output of "BaseBase".
(1)

Aniket harjai said:   1 decade ago
I think the answer shud be compilation fails because if there is a base class constructor then there shud be necessarily a derived class constructor which wud have super(); as its 1st sentence 2 make a call to base class constructor.

Sainath said:   1 decade ago
Can you explain clearly how it is executed?

Post your comments here:

Your comments will be displayed after verification.