Java Test (Beginner)

I've seen this program in a java book with tests and I can't figure out 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 error
  • D. Code works without Exit

Correct answer BaseBase

.

+3


source to share


2 answers


The first time new Alpha()

you call, you call the default constructor Alpha

. Since it is not explicitly declared, it is implicitly defined as:

public Alpha() {
    super();
}

      



Hence, it new Alpha()

calls the default constructor Base

(becauses Alpha

is a subclass Base

) that prints "Base". Then it new Base()

also calls that constructor and prints "Base" again, which results in a permanent exit from "BaseBase".

+9


source


This will be B.BaseBase's answer. The reason is simple. All objects, when instantiated, are called by the class's default constructor. Although there is no constructor in the Alpha class, java implicitly provides one and through which it calls the default constructor of its base class ie Base ().

its as an implicit super () keyword is added at the beginning of each default constructor



public Alpha() {
    super();
}

      

And so is when you call the new Base (); the corresponding output is displayed, which is in its constructor.

+3


source







All Articles