Java: Constructor

This entry is part 23 of 54 in the series Learn Java

Constructor is a special kind of method used to instantiate (construct) the object. It always has the same name as the class and does not have a return type, since it implicitly returns a new instance of the class.

To be accessible from another class not in its package it needs to be declared with the public access modifier. When a new instance of the MyRectangle class is created, by using the new syntax, the constructor method is called, which in the example below sets the fields to some default values.

package javaapplication19;

public class JavaApplication19 {

    static class MyRectangle {
        int x, y;
        public MyRectangle(int a, int b){
            x = a;
            y = b;
        public int getArea() {
            return x * y;

    public static void main(String[] args) {
        MyRectangle r = new MyRectangle(10, 20);      

        int area = r.getArea();




Series Navigation<< Java: Accessing object members
Java: Fields and members of a class >>