Supreme
Supreme

Reputation: 109

Java test (Beginner)

I saw this program in java book with tests and i can't understand, why this is the correct answer:

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 */
    } 
}

All answers:

Тhe correct answer is BaseBase.

Upvotes: 3

Views: 296

Answers (2)

Kumar Kailash
Kumar Kailash

Reputation: 1395

It would be answer B.BaseBase. Reason is simple. All the objects when instantiated it calls the default constructor of the class. Though there is no constructor in class Alpha, java implicitly provides one and through which it calls the default constructor of its base class i.e Base().

its like an implicit super() keyword is added at the beginning of every default constructors

public Alpha() {
    super();
}

And same ways when you call new Base(); respective output is shown which is in its constructor.

Upvotes: 3

Dici
Dici

Reputation: 25950

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 outpu of "BaseBase".

Upvotes: 9

Related Questions