Constructor

In Java, objects are constructed. Every time you make a new object, at least one constructor is invoked. Every class has a constructor, although if you don’t create one explicitly, the compiler will build one for you (without any parameter) – the default constructor.

You can make use of the constructor to initialize the newly created object by setting the initial state of the object, and you can acquire some resources (such as file handles). The main rule of constructors is that they should have the same name as the class. A class can have more
than one constructor

ITCuties - Java Constructor

ITCuties – Java Constructor

Constructor Declarations

package com.javalatte.itcuties.constructor;

public class ItCuties {

    protected ItCuties() {

    }

    //This is badly named but legal method, because it has no return type
    protected void ItCuties() {

    }
}
  • Constructor declarations can however have all of the normal access modifiers, and they can take arguments (including var-args), just like methods
  • A constructor can’t ever have a return type
  • They must have the same name as the class in which they are declared
  • Constructors can’t be marked static
  • Constructors can’t be marked final or abstract because they can’t be overridden

Here are some legal and illegal constructor declarations:

ItCuties(){ }
private ItCuties(int i){ }
ItCuties(float x){ }
ItCuties(int x, int ... y){  }
   
void ItCuties(){  } // method
ItCuties(); // look like abstract method
static ItCuties() { } // can't be static
final ItCuties() {  } // can't be final
abstract ItCuties() { } // can't be abstract

Java Constructor Basics

Every class, including abstract classes, MUST have a constructor. Store this into your brain. It is not necessarily to type it just because class must have one.
Objects are constructed. You can’t make a new object without invoking a constructor. In fact, you can’t make a new object without invoking not just the constructor of the object’s actual class type, but also the constructor of each of its superclasses! Constructors are the code that runs whenever you use the keyword new.

A constructor looks like this:

public class ItCuties {

ItCuties() {   }

}

Two things to remember about constructor

  1. They have no return type
  2. Their names must exactly match the class name
package com.javalatte.itcuties.constructor;

public class Student {

    private final String name;
    private final int age;

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

If you noticed, Student class does not have a no-arg constructor. This means the following statement would fail

Student stu = new Student();

but the following will compile

Student stu = new Student("Charlie", 23);

Because when you don’t write any constructor, the compiler will write no-arg constructor for you but when you write parameterized constructor, it is your responsibility to write no-arg constructor because compiler won’t generate it.

package com.javalatte.itcuties.constructor;

public class StudentDemo {

    public static void main(String[] JavaLatte) {
        // Student stu = new Student();

        Student stu = new Student("Charlie", 23);
    }
}

When Default Constructor Will Be Created

1. No default constructor would be created because it is already there.

public class Person {
	public Person() {
   	
	}

   	Person(String name) {

	}
}

2. No default constructor would be created because parameterized constructor is present.

public class Person {
	Person(String name) {
   	
	}
}

3. The compiler will generate a default constructor for the Person class, because the class doesn’t have any constructors defined.

public class Person {

}

4. The compiler will generate a default constructor for the Person class because void Person() is a method that happens to have the same name as the class

public class Person {
	void Person() {

	}
}

Java Constructor Chaining

We know constructor is invoked at runtime when we say new on some class.

Person per = new Person();

What really happen when we say new Person();. Assume Person extends Human class and Human extends Object.

  1. Person constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super().
  2. Human constructor is invoked.
  3. Object constructor is invoked.
  4. Object instance variable are given explicit values i.e, the values we explicity assigned.
  5. Object constructor is completed.
  6. Human instance variables are given their explicit values.
  7. Human constructor is completed.
  8. Person instance variables are given their explicit values.
  9. Person constructor is completed

This constructor chaining can be well understood with this example ConstructorChaining.java

package com.javalatte.itcuties.constructor;

class Human {

    String name;

    Human() {
        System.out.println("Human no-arg construtor completes");
    }

    Human(String name) {
        this.name = name;
        System.out.println("instance variables are given their explicit values");
        System.out.println("Human one-arg construtor completes");
    }
}

class Person extends Human {

    int age;

    Person() {
        System.out.println("Person no-arg construtor completes");
    }

    Person(String name, int age) {
        super(name); // super class constructor is called
        this.age = age;
        System.out.println("instance variables are given their explicit values");
        System.out.println("Person one-arg construtor completes");
    }
}

public class ConstructorChaining {

    public static void main(String[] JavaLatte) {
        Person p = new Person("Charlie", 6);
        System.out.println("Name : " + p.name + " Age: " + p.age);
    }
}

From the above discussion, here is the summary of rules that constructor follow

  • Constructors can use any access modifier, including private.
  • The constructor name must match the name of the class.
  • Constructors must not have a return type.
  • It’s legal (but stupid) to have a method with the same name as the class, but that doesn’t make it a constructor. If you see a return type, it’s a method rather than a constructor.
  • If you don’t type a constructor into your class code, a default constructor will be automatically generated by the compiler.
  • The default constructor is ALWAYS a no-arg constructor.
  • If you want a no-arg constructor and you’ve typed any other constructor(s) into your class code, the compiler won’t provide the no-arg constructor for you.
  • Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()), although remember that this call can be inserted by the compiler.
  • If you do type in a constructor and you do not type in the call to super() or a call to this(), the compiler will insert a no-arg call to super() for you, as the very first statement in the constructor.
  • A call to super() can be either a no-arg call or can include arguments passed to the super constructor.(see ConstructorChaining.java)
  • You cannot make a call to an instance method, or access an instance variable, until after the super constructor runs.
  • Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated. (see AbstractConstructorDemo.java)
  • The only way a constructor can be invoked is from within another constructor. (see AbstractConstructorDemo.java)

AbstractConstructorDemo.java

package com.javalatte.itcuties.constructor;

abstract class Animal {

    Animal() {
        System.out.println("Abstract class constructor called");
    }
}

class Dog extends Animal {

    String dogName;

    Dog() {
        System.out.println("Dog no-arg constructor");
    }

    Dog(String name) {
        this(); //constructor is called from another constructor
        dogName = name;
        System.out.println("Dog one-arg constructor");
    }
}

public class AbstractConstructorDemo {
    public static void main(String[] JavaLatte) {
        Dog dog = new Dog("Tommy");
    }
}

Java Overloaded constructor

If you notice above, we have overloaded the constructor by declaring parameterized constructor with different arguments.
Here is another examples to illustrate overloading of constructor
OverloadConstructorDemo.java

package com.javalatte.itcuties.constructor;

class Car {

    String nameOfCar;
    String modelOfCar;
    String engineOfCar;

    Car() {
    }

    Car(String nameofCar) {
        this.nameOfCar = nameofCar;
    }

    Car(String nameofCar, String modelOfCar) {
        this.nameOfCar = nameofCar;
        this.modelOfCar = modelOfCar;
    }

    Car(String nameOfCar, String modelOfCar, String engineOfCar) {
        this.nameOfCar = nameOfCar;
        this.modelOfCar = modelOfCar;
        this.engineOfCar = engineOfCar;
    }

}

public class OverloadConstructorDemo {

    public static void main(String[] JavaLatte) {
        Car c1 = new Car("BMW");
        Car c2 = new Car("BMW", "2014");
        Car c3 = new Car("BMW", "2014", "1200cc");
    }
}

Four different constructor means 4 ways to create Car object.

Download this sample code here.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>