Course contentsShow
← Java
Lesson 311 of 2,8708. Classes and EncapsulationFree lesson

Constructor Syntax: Name and Parameters

Understanding constructor syntax rules: same name as class, no return type, parameter lists.

Constructor Syntax: Name and Parameters

You'll learn: The specific syntax rules that make a method a constructor instead of a regular method.

What Makes a Constructor Special?

Constructors follow strict syntax rules that distinguish them from ordinary methods. Think of it like a driver's license: it has specific required fields (name, photo, signature) that make it valid — miss one and it won't work. Constructors have similar "must-have" requirements.

The Three Core Rules

1. Same Name as the Class

The constructor must have the exact same name as the class, including capitalization:

public class Car {
    // Correct - name matches class
    public Car() {
        // constructor code
    }
    
    // WRONG - different name
    public car() {  // lowercase 'c'
        // this is just a regular method!
    }
}

2. No Return Type

Constructors have no return type — not even void. This is how Java knows it's a constructor:

public class Book {
    // Correct - no return type
    public Book() {
    }
    
    // WRONG - has return type, so it's a regular method
    public void Book() {
    }
}

3. Parameter List

Like methods, constructors can accept parameters in parentheses:

public class Person {
    // No parameters
    public Person() {
    }
    
    // With parameters
    public Person(String name, int age) {
    }
}

The parameter list follows the same rules as method parameters you've already learned.

Why These Rules Matter

These syntax requirements let Java immediately identify constructors when you use new. When you write new Person("Alice", 30), Java looks for a constructor named Person with matching parameters.

Key Takeaway: A constructor must have the exact class name, no return type (not even void), and can have any parameter list — these three rules are non-negotiable.