Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java test (Beginner)

Tags:

java

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:

  • A.Base
  • B.BaseBase
  • C.Compilation fails
  • D.The code runs with no output

Тhe correct answer is BaseBase.

like image 205
Supreme Avatar asked Dec 02 '25 21:12

Supreme


2 Answers

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".

like image 146
Dici Avatar answered Dec 04 '25 11:12

Dici


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.

like image 44
Kumar Kailash Avatar answered Dec 04 '25 11:12

Kumar Kailash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!