Given:
class X {}
class Y {Y() {}}
class Z {z(int i )
{} }
Which class has
a default constructor?
A.
X only
X only
B.
Y only
Y only
C.
Z only
Z only
D.
X and Y
X and Y
E.
Y and Z
Y and Z
F.
X and Z
X and Z
G.
X, Y and Z
La risposta è G.X, Y and Z
X ovviamente ha un costruttore di deafult, Z lo stesso perchè il metodo è z (minuscolo). Y ha un costruttore senza parametri e argomenti, quindi ha il costruttore di dafult.
I think, the response is F (X and Z), because, Y already has a constructor. Compiler not need to assign default constructor.
RispondiEliminaThis question it's hard and I do not know what the answer is correct.
RispondiEliminaI think I also wrong in my exam ...
now:
{X} certainly has the default constructor.
For Z there are two variants of examination questions:
Z {z (int i) {}} and
Z {Z (int i) {}}
in the first case (Z {z (int i) {}}) Z HAS a default constructor.
in the second case (Z {z (int i) {}}) Z does not have a default constructor.
Y {Y () {}} has a default constructor?
I found in some books (now I can not remember which) that declare an empty constructor is to have a default constructor.
I'M NOT SURE OF THIS ...
Answer is A. X only
RispondiEliminaFrom (https://today.java.net/article/2012/08/18/default-constructors-mala-gupta-author-oca-java-se-7-programmer-i-certification-guide) I quote this:
"Exam Tip Java defines a default constructor if and only if you don't define any constructor. If a class doesn't define a constructor, the compiler will add a default, no-argument constructor to the class. But if you modify the class later by adding a constructor to it, Java compiler will remove the default, no-argument constructor that it initially added to the class. "
X has a default constructor (not defined by user)
Y has a "user-defined constructor" though it has no args.
Z has a "user-defined constructor" with an int arg.
Tip: correct typing is Capilal Z method [ Z(int i) ] which is an "user-defined" constructor. Lowercase version does not compile since all methods require a return type to be specified
Another resource:
RispondiEliminahttps://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
...[The compiler automatically provides a no-argument, default constructor for any class without constructors.]...
It specifically says "any class without constructors". That´s not the same that a no-args constructor defined by the user.