Menu
Coddy logo textTech

Classes vs Objects

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 3 of 87.

A class is a blueprint that defines structure. An object is a specific instance created from that blueprint.

The class (blueprint)

public class Car {
    String brand;
    int year;
    
    public Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }
    
    public String getInfo() {
        return this.brand + " (" + this.year + ")";
    }
}

Creating objects (instances)

Car car1 = new Car("Tesla", 2023);
Car car2 = new Car("Honda", 2020);

System.out.println(car1.getInfo());  // Tesla (2023)
System.out.println(car2.getInfo());  // Honda (2020)

Each object is independent. Changing car1 does not affect car2. You can create unlimited objects from the same class, each with its own data.

challenge icon

Challenge

Medium

Create a Car class (the blueprint) and the program will create two different objects (instances) from it:

  • Fields: brand (String) and year (int)
  • A constructor that sets both fields
  • A getInfo() method returning "<brand> (<year>)"

Cheat sheet

A class is a blueprint that defines structure. An object is a specific instance created from that blueprint.

Defining a class:

public class Car {
    String brand;
    int year;
    
    public Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }
    
    public String getInfo() {
        return this.brand + " (" + this.year + ")";
    }
}

Creating objects from a class:

Car car1 = new Car("Tesla", 2023);
Car car2 = new Car("Honda", 2020);

System.out.println(car1.getInfo());  // Tesla (2023)
System.out.println(car2.getInfo());  // Honda (2020)

Each object is independent with its own data. You can create unlimited objects from the same class.

Try it yourself

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        String brand1 = scanner.nextLine();
        int year1 = Integer.parseInt(scanner.nextLine());
        String brand2 = scanner.nextLine();
        int year2 = Integer.parseInt(scanner.nextLine());
        
        Car car1 = new Car(brand1, year1);
        Car car2 = new Car(brand2, year2);
        
        System.out.println("Car 1: " + car1.getInfo());
        System.out.println("Car 2: " + car2.getInfo());
        System.out.println("Same car? " + (car1 == car2));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming