J2EEOnline J2EE

Java Certification  «Prev  Next»
Lesson 5Constructors
Objective Explain the syntax of class constructors.


Constructors are used to create instances of classes. Their syntax follows:
modifiers ConstructorName(arguments) throws Exception {
 // Constructor body
The modifiers, arguments, and throws clause are optional. The modifiers may be
  1. public,
  2. protected,
  3. private, or
  4. none (package access).
The arguments and throws clause are defined in the same way as with methods (see Module 5).
Constructors are not inherited from their superclasses; they must be defined for each class. There is one exception: if no constructors are defined for a class, then the compiler defines a default, parameterless constructor. If the class is declared as public, then the default constructor is public. Otherwise, it has no modifiers.

this() and super()

Sometimes you may want to define one constructor in terms of another. Consider the following example:
class MyClass {
     int i;
     String s;
     public MyClass(int i, String s) {
      this.i = i;
      this.s = s;
     public MyClass() {
The first MyClass() constructor sets the i and s field variables to the values of the i and s parameters.
The this identifier refers to the current instance of MyClass being created. The second MyClass() constructor creates a MyClass object using the first constructor. The this(10,"none") causes the first constructor to be invoked with the arguments of 10 and "none."
If this() is used, it must be the first statement in a constructor.
The use of super() is similar to this() except that it invokes a constructor of the class's superclass. If super() is used, it must also be the first statement in a constructor. If neither this() nor super() is supplied, an implicit super() (with no arguments) is supplied by the compiler.
This causes the superclass portion of an object to be created before that of the class itself.

Classes Constructor - Quiz

Click the Quiz link below to check your understanding of classes and constructors.
Classes Constructor - Quiz