Constructors

Are you preparing for IT certification? With practice questions, study notes, interactive quizzes, tips and technical articles, uCertify PrepKits ensure that you get a solid grasp of core technical concepts to ace your certification exam in first attempt.

Constructors

Rating:

A constructor is a special kind of method that is written as a part of a class. It provides a convenient way to initialize a newly created object at the time of its creation. Once a constructor is defined for a class, it is called automatically immediately after the creation of a new object, but before the new operator completes. All Java classes must have at least one constructor, either explicitly declared in the class or an implicit default constructor.

Constructor Declarations

Constructors are typically used to create an object that is an instance of a class. A constructor is written by using the following general syntax:

[access modifier] class name([formal parameter list]) [throws clause] {
   // Body of the constructor
}


where, the elements within square brackets are optional.

Although constructors look the same as methods, they are written by using the following conventions:

  1. A constructor is always given the name of the class in which it is defined.

  2. A constructor is always written without an explicit return type, not even void. This is because the implicit return type of a class constructor is the class itself.

  3. Only accessibility modifiers can be used to declared a constructor. Unlike methods, a constructor cannot be declared as abstract, static, final, native, strictfp, or synchronized.
For example, consider the following class definition:

  1. class Rectangle{

  2.    float length;

  3.    float breadth;

  4.     Rectangle(float x, float y){

  5.        length = x;

  6.        breadth = y;

  7.    }

  8. }
In the given code, the Rectangle class contains two instance variables named length and breadth, and a constructor that takes two arguments. The name of the constructor is exactly the same as the name of the class and it is declared without a return type.

Constructor Modifiers

The use of accessibility modifiers in the constructor declaration expression specifies what other objects can create an instance of a class. A constructor can be declared using the accessibility modifiers public, private, or protected.

  • public

    A class constructor when declared as public implies that any class can create an instance of the class.


  • private

    A class constructor when declared as private implies that no other classes can instantiate that class by calling that constructor. Such a class may contain public class methods sometimes also called factory methods. Those methods can construct an object and return it, but no other classes can do so.


  • protected

    A class constructor when declared as private implies that only subclasses of that class and classes that are in the same package can create instances of it.


  • No access modifier

    When no access modifier is used to declare a class constructor, the package access also called default access applies. A class constructor when declared without any access modifier implies that only classes that are in the same package can construct an instance of the class.
Default constructor

A constructor without any parameters is known as a default constructor. When a class is defined without any constructor, the Java compiler provides an implicit default constructor. The implicit default constructor is equivalent to the following implementation:

class name(){
   super();
}


When the implicit default constructor of a class is invoked, it implicitly calls the no parameter constructor in the superclass. This action taken by a default constructor ensures that the inherited state of the object is initialized properly. In addition, it initializes all the instance variables in the object to the default value depending on their data type.

The default constructor of a class has the same access modifier with which the class has been declared. For example, the default constructor of a public class is implicitly given the public access. The default constructor of a protected class is implicitly given the protected access. The default constructor of a private class is implicitly given the private access. Otherwise, the default constructor has the default access, which is implied by no access modifier.

Consider the following code:

class Rectangle{
   float length, breadth;
}


In the given code, the Rectangle class has been defined without any constructor. Therefore, it will be provided an implicit default constructor. Therefore, this code is equivalent to the following:

  1. class Rectangle{

  2.    float length, breath;

  3.     Rectangle(){      //default constructor

  4.        super();

  5.    }

  6. }
Once the Rectangle class has been defined, the creation of a Rectangle object by using the new operator along with the implicit default constructor will initialize all the fields of the object to their default value, i.e., the fields length and breadth in a Rectangle object will be initialized to 0.0f (the default value for the float type).

A default constructor for a class can also be explicitly defined in the class. Here is an example in which an explicit default constructor is provided for the class.

  1. class Rectangle{

  2.    float length;

  3.    float breadth;

  4.    Rectangle(){

  5.        length = 5.0f;

  6.        breadth = 3.0f;

  7.    }

  8. }
The explicit default constructor in the given code ensures that any object created with the expression new Rectangle() expression will have its fields length and breadth initialized to 5.0f and 3.0f respectively.

If a class defines any explicit constructors, the Java compiler does not provide an implicit default constructor to set the state of the objects. If the class requires a default constructor, the constructor must be explicitly defined within the class.

Overloaded Constructors

Java supports name overloading for constructors. Therefore, a class can have any number of constructors provided they differ in their parameter lists. Typically, a constructor uses its arguments to initialize the new object's state. The compiler differentiates these constructors by taking into account the number of parameters in the list and their types. For example, consider the following code:

  1. class Rectangle{

  2.    float length;

  3.    float breadth;

  4.    Rectangle(float x, float y){

  5.        length = x;

  6.        breadth = y;

  7.    }

  8.    Rectangle(float x){

  9.        length = x;

  10.        breadth = x;

  11.    }

  12. }
In the given code, two constructors have been defined in the Rectangle class. The constructor at line number 4 takes two arguments, whereas the constructor at line number 8 takes one argument. Based on the number and type of the arguments passed into the constructor, the compiler determines which constructor to use. Therefore, for the expression new Rectangle(10.0f, 8.0f) , the compiler calls the constructor that takes two arguments, i.e., the one at line number 4. For the expression new Rectangle(10.0f), the compiler calls the constructor that takes one argument, i.e., the one at line number 8.

As constructors are not members of a class, they are not inherited by subclasses. Therefore, each of the subclasses must specifically implement any constructors it needs. However, a subclass can use the constructors of its superclass by using the super keyword. For example, the Rectangle class defined above has a constructor with the following signature:

Rectangle(float x, float y)

If a subclass of the Rectangle class named SampleRectangle wants to call the constructor shown above, it can do so by defining the following constructor:

SampleRectangle(float w){
   super(10, w);
   // rest of the code
}


However, it must be noted that if an invocation of the super() constructor is used, it must always be the first executable statement in the constructor body. Otherwise, a compile-time error will occur.

The implied super() constructor

The Java compiler does a lot of work in order to compile the code within the body of a constructor. If the first line of code within the body of a constructor does not contain an invocation of the super() constructor, the compiler assumes the presence of the super() statement as the first executable statement within the body of the constructor. The super() statement is an invocation of the default constructor in the superclass. Therefore, it means that the superclass must have a no-parameter constructor.


Rating:



Other articles

Click here to Article home

 
uCertify.com | Our Company | Articles | Privacy | Security | Contact Us | News and Press Release | uCertify India
MCSE: MCSA, MCTS, MCITP    JAVA Certification: SCJP, SCWCD Cisco Certification: CCNA, CCENT, A+, Network+, Security+
Oracle Certification: OCP 9i, OCP 10g, OCA 9i, OCA 10g CIW foundation    EC-212-32    CISSP    Photoshop ACE    Adobe Flash ACE
© 2008 uCertify.com. All rights reserved. All trademarks are the property of their respective owners.