Which of these classes has a default constructor? I'm thinking just A but am I wrong?
class A {}
class B {B() {}}
class C {C(int j) {}}
Which of these classes has a default constructor? I'm thinking just A but am I wrong?
class A {}
class B {B() {}}
class C {C(int j) {}}
You are correct. A default constructor is, by definition, created when no constructor is defined. Since A
does not have a constructor defined it will have a default constructor created for it.
Technically speaking, you could say B
has a default constructor since a parameter-less constructor is what would be created if none is defined.
Reference: http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.9
Precisely.
Class A
has a default constructor because you're not providing any constructor for the class. The compiler, therefore, automatically provides a no-argument, default constructor. This default constructor will call the no-argument constructor of the superclass (in this case the Object class). The second class, Class B
, is providing a no-argument constructor, but it is not default as the compiler is not providing it for you.