What is a class and an object in Java?

A class is a blueprint which describes the data (fields) and the actions (methods). An object is a real thing made from the class with new. Many objects can be made from one class, each with its own data.

class Car {
    String model;
    int speed;

    void accelerate() {
        speed += 10;
    }
}

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

        Car c2 = new Car();
        c2.model = "Creta";

        System.out.println(c1.model + " " + c1.speed);
        System.out.println(c2.model + " " + c2.speed);
    }
}
Output

Swift 20
Creta 0

See Java Classes and Objects.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.