Constructor (Java)

A constructor is a special method that runs automatically when you create an object with new. Its job is to set up the object's initial state, such as assigning starting values to its fields.

Java

A constructor has the same name as its class and has no return type, not even void. If you don't write one, Java provides a default no-argument constructor for you.

You can have several constructors with different parameter lists (constructor overloading), and use the this keyword to refer to the current object's fields.

Examples

Java

public class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public static void main(String[] args) {
        Point p = new Point(2, 5);
        System.out.println(p.x + ", " + p.y);
    }
}

Output:

2, 5

Learn it in a lesson

See also

Back to the Dictionary