Memra

Classes, objects, new & constructors

◈ 4 cards

Blueprints vs instances — and the implicit no-arg constructor rule.

Classes are blueprints; objects are instances

A class defines the shape — fields and methods. An object is a concrete instance of that blueprint, created with new:

public class Dog {
    String name;
    int age;

    Dog(String name, int age) {
        this.name = name;
        this.age  = age;
    }

    void bark() { System.out.println(name + " says woof"); }
}

Dog rex = new Dog("Rex", 3);
rex.bark();  // Rex says woof

A constructor has the same name as the class and no return type (not even void). Its job is to initialise the new object's state.

The implicit no-arg constructor: if you write no constructors at all, Java silently provides a public no-arg constructor. The moment you write any constructor, that implicit one disappears — and any code that called new Dog() now fails to compile. This is the most common "mysterious compile error" for beginners.

what Dog declaresnew Dog()new Dog("Rex", 3)no constructorimplicit — okcompile errorDog(String, int)compile errorokboth, written outokok
The implicit no-arg constructor exists only while the class declares no constructor at all. Adding Dog(String, int) removes it, and the error then appears at every new Dog() call site.
NORMAL ~/memra/learn/java-from-zero/classes-and-objects utf-8 LF