Sail E0 Webinar
Question

Which three statements are true?

    1. The default constructor initialises method variables.

    2. The default constructor has the same access as its class.

    3. The default constructor invokes the no-arg constructor of the superclass.

    4. If a class lacks a no-arg constructor, the compiler always creates a default constructor.

    5. The compiler creates a default constructor only when there are no other constructors for the class.



Options:
A .  1, 2 and 4
B .  2, 3 and 5
C .  3, 4 and 5
D .  1, 2 and 3
Answer: Option B


(2) sounds correct as in the example below


class CoffeeCup {
private int innerCoffee;
public CoffeeCup() {
}
public void add(int amount) {
innerCoffee += amount;
}
//...
}


The compiler gives default constructors the same access level as their class.



In the example above, class CoffeeCup is public, so the default constructor is



public. If CoffeeCup had been given package access, the default constructor would



be given package access as well.



(3) is correct. The Java compiler GENERATES at least one instance initialisation



method for every class it compiles. In the Java class file, the instance initialisation



method is named "." For each constructor in the source code of a class, the Java



compiler generates one () method. If the class declares no constructors explicitly,



the compiler generates a default no-arg constructor that just invokes the superclass's



no-arg constructor. As with any other constructor, the compiler creates an () method



in the class file that corresponds to this default constructor.



(5) is correct. The compiler creates a default constructor if you do not declare any



constructors in your class.



Was this answer helpful ?
Next Question

Submit Solution

Your email address will not be published. Required fields are marked *

Latest Videos

Latest Test Papers