Consider the following constructor. Which of the following correctly creates a Building object and stores its reference?
public Building(int no, String nm)
Building b = Building(3, "E");Building b = new Building(3, "E");new b = Building(3, "E");Building(3, "E") = new b;new Building(3, "E") calls the constructor and creates an object whose reference is stored in b.
Explanation
The keyword new calls a constructor and creates an object. The declaration on the left supplies the reference variable and its type, and the assignment stores the produced reference in that variable.
- A is not correct: leaving out
newdoes not create an object, so this is not a constructor call and there is no reference to store. - C is not correct: the keyword
newis not a type, so it cannot begin a declaration; the class nameBuildinggives the reference variable its type. - D is not correct: a constructor call cannot appear on the left of an assignment; the reference produced by
newis stored into the declared variable.