Java Reference
In-Depth Information
Table 6-6.
Examples of Classes for Which a Default Constructor Is Added by the Java Compiler
Source Code for Your Class
Compiled Version of Your Class
Comments
public class Test {
}
public class Test {
public Test() {
}
}
The compiler adds a default constructor with
public
access level.
class Test {
}
class Test {
Test() {
}
}
The compiler adds a default construct with
package-level access.
public class Test {
Test() {
}
}
public class Test {
Test() {
}
}
The
Test
class already had a constructor. The
compiler does not add any constructor.
public class Test {
public Test(int x) {
}
}
public class Test {
public Test(int x) {
}
}
The
Test
class already had a constructor. The
compiler does not add any constructor.
public class Test {
private class Inner {
}
}
public class Test {
public Test() {
}
private class Inner {
private Inner(){
}
}
}
Test
is a public top-level class and
Inner
is
a private inner class. The compiler adds a
public
default constructor for the
Test
class
and a
private
default constructor for the
Inner
class.
■
It is good programming practice to add a constructor explicitly to all your classes rather than letting the compiler
add a default constructor for your classes. the story of constructors is not over yet. You will revisit constructors in the
chapter on inheritance.
Tip
A static Constructor
Constructors are used in the context of the creating a new object; hence, it is consider part of the object context, not
the class context. You cannot declare a constructor
static
. The keyword
this
, which is a reference to the current
object, is available inside the body of a constructor as it is available inside the body of an instance method.