Constructors

suggest change

Constructors are named after the class, have no return type, and initialize new objects. Like methods, they can take parameters. Abstract classes can have constructors too. A constructor is not itself a method.

public class Hello{
    // constructor
    public Hello(String wordToPrint){
        printHello(wordToPrint);
    }
    public void printHello(String word){
        System.out.println(word);
    }
}
// Instantiating the object calls the constructor, which prints wordToPrint.

It is important to understand that constructors are different from methods in several ways:

  1. Constructors can only take the modifiers public, private, and protected, and cannot be declared abstract, final, static, or synchronized.
  2. Constructors do not have a return type.
  3. 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.
  4. 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents