Classes and Objects

Blueprints and real things

Java is an object-oriented language. That means programs are built from objects that hold data and can do things.

Think of it like this: A class is like the blueprint of a car: it says every car has a colour and a speed, and can drive. An object is one real car built from that blueprint – a red one, a blue one. One blueprint, many cars.

Writing a class

class Dog {
    String name;
    int age;

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

public class Main {
    public static void main(String[] args) {
        Dog d1 = new Dog();
        d1.name = "Bruno";
        d1.age = 3;

        Dog d2 = new Dog();
        d2.name = "Tiger";
        d2.age = 5;

        d1.bark();
        d2.bark();
        System.out.println(d2.name + " is " + d2.age);
    }
}

Output

Bruno says Woof!
Tiger says Woof!
Tiger is 5
WordMeaningHere
classthe blueprintDog
fielda piece of data every object hasname, age
methodsomething every object can dobark()
objectone real thing made from the classd1, d2
newbuild a new objectnew Dog()

Each object has its own copy of the fields. Changing d1.name doesn't touch d2.

Tip: In this course everything goes in one file, so other classes are written without public. In real projects, each public class usually gets its own file, like Dog.java.

HOME LABS COMMUNITY DASHBOARD