What is a Class in Java?

A class in Java is a blueprint or template used to create objects. It is not an actual entity but a design, just like how an architect creates a design before constructing a building. The building design represents a class, and the actual buildings represent objects.

A class contains:

  • Fields (Variables): These store the data or state of an object. Each object created from a class has its own copy of these variables.
  • Methods: These define the behavior of an object—how it will act or respond.
  • Constructor: A special method used to initialize objects. It is automatically called when an object is created.

Example :

// Defining a Class
class Bike{
    // Instance Variables (State)
    String brand;
    int speed;
    String color;

    // Method (Behavior)
    void display() {
        System.out.println("Bike Brand: " + brand);
        System.out.println("Bike Speed: " + speed);
        System.out.println("Bike Color: " + color);
    }
}

In this example:

display() is a method that shows the behavior of the object.

Bike is a class.

brand, speed, and color are fields representing the state.

👉 For a detailed explanation with examples, read the full post on Java Classes

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
AITECHRAY