Constructors are Methods that are used to instantiate/initialise Objects with default Attributes. By default, most Object Oriented Programming Languages come with a default constructor, which is automatically generated by the compiler.

Most OO languages allow Method Overloading in constructors, i.e. multiple constructors in the same class. However, constructors cannot be overridden!

Even though they sound similar, overloading a constructor is very different from overriding one (which isn't possible!)

Syntax

In Java, a constructor:

  • must be the same name as the class it belongs to
  • does not have a return type (not even void!)

Java Keywords#todo Java uses the keyword this to avoid double ups.#todo

Default Constructors

In Java, the default constructor does the following:

Copy Constructor

#todo Is a constructor with a single argument of the same type as the class Creates a separate copy of the object sent as input The copy constructor should create an object that is a separate, independent object, but with the instance variables set so that it is an exact copy of the argument object

Examples

public class Person 
{
	int age; //Setting it here doesn't do anything, it gets overrided by the constructor
 
	public Person() 
	{
		age = 5; //Default age is now always 5
	}
 
	//using [Method Overloading](Method%20Overloading.md)
	public Person(int age) 
	{
		this.age = age; //See [Java Keywords](Java%20Keywords.md)
	}
	
}