Object-Oriented Programming

Constructors

A constructor initializes objects when they're created.

Default Constructor

public class Car {
    String brand;
    
    // Constructor
    public Car() {
        brand = "Unknown";
    }
}

Parameterized Constructor

public class Car {
    String brand;
    String color;
    
    public Car(String brand, String color) {
        this.brand = brand;
        this.color = color;
    }
}

// Usage
Car myCar = new Car("Toyota", "Red");

The
this
Keyword

Refers to the current object:

  • this.brand
    = the object's brand field
  • brand
    = constructor parameter
Visualizer
function
Person()
"Alice"
25
Person object

Interactive Visualization

java
Loading...
Output
Run execution to see output...