Class and Object in Java

A class is a blueprint that defines fields (data) and methods (behaviour). An object is an instance of a class: a real entity created in memory with new.

AnalogyClass = the design of a car. Objects = the actual cars built from that design.
Car (class)String colorString modelint speedvoid run()new Car()c1 : Carcolor = "Red"model = "Swift"speed = 80c2 : Carcolor = "Blue"model = "City"speed = 60
One class (blueprint) — many objects (instances)
Java
class Car {
    String color, model;
    int speed;

    void run() {
        System.out.println(color + " " + model + " running at " + speed + " km/h");
    }
}

public class Main {
    public static void main(String[] args) {
        Car c1 = new Car();
        c1.color = "Red"; c1.model = "Swift"; c1.speed = 80;

        Car c2 = new Car();
        c2.color = "Blue"; c2.model = "City"; c2.speed = 60;

        c1.run();
        c2.run();
    }
}
Red Swift running at 80 km/h Blue City running at 60 km/h

Ways to Create an Object

  • Using new (most common)
  • Using clone()
  • Using reflection (newInstance())
  • Using deserialization
Track your progress through the Java course