Constructors

JavaA constructor is a special type of method that is executed when an object is created. The purpose of constructors is to assign values to the fields that are specific to that particular instance of the object. For instance, if you are creating a Car object, you may need to tell the program what brand the car is, what color it is, how fast it is going, and in what direction it is traveling. A constructor allows you to do these things easily when the object is created during program execution.

Saying that a constructor is a method is like saying that the Australian platypus is just another mammal. To understand the platypus, it is important to know how it is different from other mammals. To understand the constructor, it is similarly important to understand how it differs from a method. Any student of Java, especially one studying for certification, needs to know those differences; in this article, I will concretely spell them out.

Purpose and function

Constructors have one purpose in life: to create an instance of a class. This can also be called creating an object, as in:

Platypus p1 =newPlatypus();

The purpose of methods, by contrast, is much more general. A method’s basic function is to execute Java code.

Signature differences

Constructors and methods differ in three aspects of the signature: modifiers, return type, and name. Like methods, constructors can have any of the access modifiers: public, protected, private, or none (often called package or friendly). Unlike methods, constructors can take only access modifiers. Therefore, constructors cannot be abstractfinalnativestatic, or synchronized.

The return types are very different too. Methods can have any valid return type, or no return type, in which case the return type is given as void. Constructors have no return type, not even void.

Finally, in terms of the signature, methods and constructors have different names. Constructors have the same name as their class; by convention, methods use names other than the class name. If the Java program follows normal conventions, methods will start with a lowercase letter, constructors with an uppercase letter. Also, constructor names are usually nouns because class names are usually nouns; method names usually indicate actions.

The use of “this”

Constructors and methods use the keyword this quite differently. A method usesthis to refer to the instance of the class that is executing the method. Static methods do not use this; they do not belong to a class instance, so this would have nothing to reference. Static methods belong to the class as a whole, rather than to an instance. Constructors use this to refer to another constructor in the same class with a different parameter list. Study the following code:

public class Platypus {
 String name;

 Platypus(String input){ name = input;
 }

 Platypus(){ 
  this("John/Mary Doe");
 }

 public static void main(String args[]){

 Platypus p1 =newPlatypus("digger");

 Platypus p2 =newPlatypus();

 }
}

In the code, there are two constructors. The first takes a String input to name the instance. The second, taking no parameters, calls the first constructor by the default name "John/Mary Doe".

If a constructor uses this, it must be in the constructor’s first line; ignoring this rule will cause the compiler to object.

The use of “super”

Methods and constructors both use super to refer to a superclass, but in different ways. Methods use super to execute an overridden method in the superclass, as the following example illustrates:

class Mammal{

 void getBirthInfo() { 
  System.out.println("born alive.");
 }

}

class Platypus extends Mammal {

 void getBirthInfo(){

 System.out.println("hatch from eggs");

 System.out.print("a mammal normally is ");

 super.getBirthInfo();
 }
}

In the above program, the call to super.getBirthInfo()calls the overridden method of the Mammal superclass.

Constructors use super to invoke the superclass’s constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain. An example follows:

public class SuperClassDemo {

 SuperClassDemo(){

 }

}

class Child extends SuperClassDemo {
 
 Child() {
  super();
 }

}

In the above (and trivial!) example, the constructor Child() includes a call to super, which causes the class SuperClassDemo to be instantiated, in addition to the Childclass.

Compiler-supplied code

The new Java programmer may stumble when the compiler automatically supplies code for constructors. This happens if you write a class with no constructors; the compiler will automatically supply a no-argument constructor for you. Thus, if you write:

public class Example{}

The compiler also automatically supplies code when you do not use super (using zero or more parameters) as the first line of a constructor. In this case, the computer automatically inserts super. Thus, if you write:

public class TestConstructors {

 TestConstructors(){

 }

}

it is functionally equivalent to writing:

public class TestConstructors {

 TestConstructors(){
  super;
 }

}

The sharp-eyed beginner may wonder how the above program can call the parent class’s constructor when TestConstructor is not extending any class. The answer is that Java extends the Object class when you do not explicitly extend a class. The compiler automatically supplies a no-argument constructor if no constructor is explicitly declared, and automatically supplies a no-argument super call when a constructor has no explicit call to super. So the following two code snippets are functionally equivalent:

public class Example{}

and

public class Example {

 Example(){
  super;
 }

}

Inheritance

What is wrong with the following scenario? A lawyer is reading the will of A. Class. Members of the Class family are gathered around a large conference table, some sobbing gently. The lawyer reads, “I, A. Class, being of sound mind and body, leave all my constructors to my children.”

The problem is that constructors cannot be inherited. Fortunately for the Classchildren, they will automatically inherit any of their parents’ methods, so the Classchildren will not become totally destitute.

Remember, Java methods are inherited, constructors are not. Consider the following class:

public class Example { 

 public void sayHi {
  System.out.println("Hi");
 }

 Example() {

 }
}

public class SubClass extends Example{}

The SubClass class automatically inherits the sayHi method found in the parent class. However, the constructor Example() is not inherited by the SubClass.

Summarizing the differences

Just as the platypus differs from the typical mammal, so too do constructors differ from methods; specifically in their purpose, signature, and use of this and super. Additionally, constructors differ with respect to inheritance and compiler-supplied code. Keeping all these details straight can be a chore; the following table provides a convenient summary of the salient points.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s