ConstructorsHomepage  « Learn Java5 « Constructors

In this lesson we look at constructors, which are used to create instances of our classes.

In the last lesson we looked at instance variables and how we use them to populate our objects. We created three Cat objects using the new keyword to create our instances and then used quite a few lines of code to create state for each object. Part of the TestCat4 test class is shown below:

instance population

This approach to creating state within our objects is not only long winded but prone to error. There is also another thing I am sure you have been wondering about, each time we create an instance of an object we use parentheses after the name of the object we are instantiating. It looks like we are calling a method to create our object! Lets look at the steps in creating an object again:

object creation2

Default Constructorgo to top of page Top

So what is going on here? It sure looks like we are calling a method called Cat(). Well actually we're calling the Cat constructor, which has the code that runs when you instantiate an object by using the new keyword followed by a class name. I know what you're thinking, we haven't written any constructor for our Cat class, so what is going on here? Well if we don't write our own constructor, our friendly compiler writes a default constructor for us. The default constructor always follows the same pattern, which is the public access modifier followed by the class name and empty parentheses. So for our Cat class the the compiler added the following code:

default constructor

This looks like a method but there's something missing, the return type which is mandatory for a method. So, if we don't write our own constructor then the compiler will insert a no arguments constructor into our code for us, which is how we have been able to construct instances of our Cat class so far.

Coding Our Own Constructorsgo to top of page Top

Lets code our own constructor for our Cat class and use it to create state within some Cat objects. To do this we are going to amend our existing Cat class and then write a new test class to ensure it all works.


/*
  A Cat Class
*/ 
public class Cat {
    String name, colour;
    int age;
    /*
      Below is the new constructor for our Cat Class
    */ 
    public Cat(String a, String b, int c) {
        name = a;
        colour = b;
        age = c;
    }
    
    void talk() {
	System.out.println("meow!");
    }
}

Save and compile our amended Cat class in directory   c:\_ObjectsAndClasses in the usual way.

What we have done is create a new constructor for our Cat class (notice there is no return type). The constructor has three parameters for the name, age and colour of the cat. Inside the constructor we assign the parameters to our Cat instance variables. Now lets test our new Cat class:


/*
  Test Class5 for Cat
*/ 
public class TestCat5 {

    public static void main (String[] args) {
        Cat moggy = new Cat("Henry", "black", 4);   // Call new Cat constructor with three arguments
        Cat tigger = new Cat("Kitty", "black", 15); // Call new Cat constructor with three arguments
        Cat tabby = new Cat("Felix", "white", 8);   // Call new Cat constructor with three arguments
        System.out.println("Our " + moggy.colour + " cat called " + moggy.name + " is " + moggy.age);
        System.out.println("Our " + tigger.colour + " cat called " + tigger.name + " is " + tigger.age);
        System.out.println("Our " + tabby.colour + " cat called " + tabby.name + " is " + tabby.age);
    }
}

Save, compile and run the file in directory   c:\_ObjectsAndClasses in the usual way.

run cat class with constructor

The above screenshot shows the output of running our TestCat5 class. We created three new Cat instances by passing across three arguments to the Cat constructor and then printed off the state of the new objects. As you can see there are a lot less lines of code now.

Overloaded Constructorsgo to top of page Top

This isn't the end of the story though, not by a long chalk. Lets enhance our test class above to call a Cat object with no arguments:


/*
  Test Class5 for Cat
*/ 
public class TestCat5 {

    public static void main (String[] args) {
        Cat moggy = new Cat("Henry", "black", 4);   // Call new Cat constructor with three arguments
        Cat tigger = new Cat("Kitty", "black", 15); // Call new Cat constructor with three arguments
        Cat tabby = new Cat("Felix", "white", 8);   // Call new Cat constructor with three arguments
        Cat tommy = new Cat();  // Call Cat constructor with no arguments
        System.out.println("Our " + moggy.colour + " cat called " + moggy.name + " is " + moggy.age);
        System.out.println("Our " + tigger.colour + " cat called " + tigger.name + " is " + tigger.age);
        System.out.println("Our " + tabby.colour + " cat called " + tabby.name + " is " + tabby.age);
        System.out.println("Our " + tommy.colour + " cat called " + tommy.name + " is " + tommy.age);
    }
}

Save and compile the file in directory   c:\_ObjectsAndClasses in the usual way.

run cat class with no args constructor

The above screenshot shows the output of compiling our TestCat5 class. Whoa! What happened here? It has given us an error when we try to create a new Cat object using a no arguments constructor?? It appears from the error that the compiler was looking for a constructor with (String,String,int). But doesn't the compiler put in a default no arguments constructor for us? No it doesn't, as soon as we code our own constructor the compiler doesn't get involved and leaves construction to us. So if we want a default no arguments constructor as well we have to code it. Ok lets do just that:


/*
  A Cat Class
*/ 
public class Cat {
    String name, colour;
    int age;
    /*
      no-arg constructor for our Cat Class
    */ 
    public Cat() {

    }

    /*
      Below is the new constructor for our Cat Class
    */ 
    public Cat(String a, String b, int c) {
        name = a;
        colour = b;
        age = c;
    }
    
    void talk() {
	System.out.println("meow!");
    }
}

Save and compile our revised Cat class in directory   c:\_ObjectsAndClasses in the usual way.

We now have two constructors in our Cat class. When a class has more than one constructor they are known as overloaded constructors. Each constructor must have different argument lists so the compiler knows which constructor to use to construct our objects. Having the same argument types is fine as long as the order differs. OK, our TestCat5 class should compile fine now, so compile and run it:

run cat class with two constructor

The above screenshot shows the output of running our TestCat5 class. As you can see from the output we now have a fourth line of output for a Cat object, which was instantiated using our no-arg constructor with default values.

Using the this Keywordgo to top of page Top

We are not finished with constructors just yet. When we call a method or constructor, it is automatically passed an implicit reference to the invoking object, or put another way, to the instance whose method or constructor is being called. As such you can refer to any member of the current object from within an instance method or constructor by using the this keyword. Ok to get our heads around this lets revamp our Cat class.


/*
  A Cat Class
*/ 
public class Cat {
    String name, colour;
    int age;
    /*
      no-arg constructor for our Cat Class
    */ 
    public Cat() {

    }

    /*
      Constructor using this Keyword
    */ 
    public Cat(String name, String colour, int age) {
        this.name = name;
        this.colour = colour;
        this.age = age;
    }
    
    void talk() {
	System.out.println("meow!");
    }
}

Save and compile our revamped Cat class in directory   c:\_ObjectsAndClasses in the usual way.

Run our TestCat5 class again:

using this 1

The above screenshot shows the output of running our TestCat5 class which is exactly the same as before. We have changed the parameters to the Cat object to match our instance variables, which is a lot more meaningful than using a, b and c and used the this keyword to assign these values to the current object. These way of construction seems a lot more intuitive.

Calling this()go to top of page Top

We can also invoke one constructor from another constructor within the same class using this() and doing so is known as explicit constructor invocation. If we decide to use this() it must be the first statement within our constructor or we get a compiler error. We can show an example of this using our trusty old Cat class. Lets assume for the purposes of this example that we always know a cat's colour and age but can't always be sure of a cat's name. We could pass across a string to our three argument constructor for the name such as "unknown" to cater for this. But what if someone using our Cat class didn't know of this rule and just had a cat's colour and age? How do we get around this? Well we create a two argument constructor for this purpose and do the populating of the Cat's name in there. We then call our three argument constructor from it using this(). Lets code this scenario into our Cat class.


/*
  A Cat Class
*/ 
public class Cat {
    String name, colour;
    int age;
    /*
      no-arg constructor for our Cat Class
    */ 
    public Cat() {

    }

    /*
      Our new constructor for when someone using our class doesn't know the name of a cat
    */ 
    public Cat(String colour, int age) {
        this("unknown", colour, age);
    }

    /*
      Constructor using this Keyword
    */ 
    public Cat(String name, String colour, int age) {
        this.name = name;
        this.colour = colour;
        this.age = age;
    }
    
    void talk() {
	System.out.println("meow!");
    }
}

Save and compile our reworked Cat class in directory   c:\_ObjectsAndClasses in the usual way.

We now need to enhance our test class to test the above changes to our Cat class out:


/*
  Test Class5 for Cat
*/ 
public class TestCat5 {

    public static void main (String[] args) {
        Cat moggy = new Cat("Henry", "black", 4);   // Call new Cat constructor with three arguments
        Cat tigger = new Cat("Kitty", "black", 15); // Call new Cat constructor with three arguments
        Cat tabby = new Cat("Felix", "white", 8);   // Call new Cat constructor with three arguments
        Cat tommy = new Cat();  // Call Cat constructor with no arguments
        Cat bobby = new Cat("beige", 6);  // Call Cat constructor with colour and age
        System.out.println("Our " + moggy.colour + " cat called " + moggy.name + " is " + moggy.age);
        System.out.println("Our " + tigger.colour + " cat called " + tigger.name + " is " + tigger.age);
        System.out.println("Our " + tabby.colour + " cat called " + tabby.name + " is " + tabby.age);
        System.out.println("Our " + tommy.colour + " cat called " + tommy.name + " is " + tommy.age);
        System.out.println("Our " + bobby.colour + " cat called " + bobby.name + " is " + bobby.age);
    }
}

Save, compile and run the file in directory   c:\_ObjectsAndClasses in the usual way.

run cat class calling a constructor with this

The above screenshot shows the output of running our TestCat5 class. This is a much more elegant approach than calling the three argument constructor everytime with a name of "unknown". What if, down the line you decided to use "anonymous" instead of "unknown". Wherever you had called the three argument constructor in your code with a name of "unknown" you would have to change the code whereas with the constructor approach you change the code in one place.

Constructors Checklistgo to top of page Top


  • A constructor runs when we code new operator followed by a class name.
  • Constructors must have the same name as the class and no return type.
  • Constructors are used to initialize the instance variables (object state) of the object instance being constructed.
  • If you don't code a constructor in your class the compiler will put in a default no arguments constructor.
  • If you do code a constructor in your class, the compiler will NOT put in a default no arguments constructor, you will have to code it yourself.
  • We can have more than one constructor in a class and the constructors are then known as overloaded constructors.
  • When using overloaded constructors in a class, each constructor must have different argument lists so the compiler knows which constructor to use to construct our objects. Having the same argument types is fine as long as the order differs.
  • You can refer to any member of the current object from within a non-static method or constructor by using the this keyword.
  • You can invoke one constructor from another constructor within the same class by calling this() and doing so is known as explicit constructor invocation.
  • If we decide to use this() it must be the first statement within our constructor or we get a compiler error. This means we can't use this() and super() together.

This isn't the end of the story for constructors, we will look at superclass constructors when we look at OO Concepts in the next section.

Constructors Quizgo to top of page Top

Try the quiz below to test your knowledge of this lesson

Question 1 : How many parameters in a default constructor?
- The default constructor has no parameters.
Question 2 : What differentiates a constructor and a method?
- constructors have no return type.
Question 3 : The compiler always provides a default no-arg constructor?
- The compiler only provides a default no-arg constructor when no other constructors are present.
Question 4 : When you have more than one constructor in a class these are known as?
- When you have more than one constructor in a class these are known as overloaded constructors.
Question 5 : What does the keyword this refer to?
- The keyword <code>this</code> refers to the current object.
Question 6 : When using overloaded constructors what must we ensure?
- When using overloaded constructors we must ensure that they have different argument lists, so the compiler can differentiate between them.
Question 7 : We invoke constructors within the same class using the new keyword?
- We invoke constructors within the same class using the <code>this</code> keyword
Status Bar Please select an answer

What's Next?

In the next lesson we investigate static members.

<<  Instance Variables & Scope                    Static Members  >>

go to home page Java5 Tutor Homepage go to top of page Top