Constructors are special methods named after the class and without a return type, and are used to construct objects. Constructors, like methods, can take input parameters. Constructors are used to initialize objects. Abstract classes can have constructors also.
public class Hello{
// constructor
public Hello(String wordToPrint){
printHello(wordToPrint);
}
public void printHello(String word){
System.out.println(word);
}
}
// instantiates the object during creating and prints out the content
// of wordToPrint
It is important to understand that constructors are different from methods in several ways:
Constructors can only take the modifiers public
, private
, and protected
, and cannot be declared abstract
, final
, static
, or synchronized
.
Constructors do not have a return type.
Constructors MUST be named the same as the class name. In the Hello
example, the Hello
object's constructor name is the same as the class name.
The this
keyword has an additional usage inside constructors. this.method(...)
calls a method on the current instance, while this(...)
refers to another constructor in the current class with different signatures.
Constructors also can be called through inheritance using the keyword super
.
public class SuperManClass{
public SuperManClass(){
// some implementation
}
// ... methods
}
public class BatmanClass extends SupermanClass{
public BatmanClass(){
super();
}
//... methods...
}
See Java Language Specification #8.8 and #15.9