What is Class in Java with Examples

Introduction

In Java, a class is a blueprint or template that defines the structure and behavior (attributes and methods) that the objects created from the class can have. A class encapsulates data for the object and methods to manipulate that data. It serves as the fundamental building block in object-oriented programming (OOP) in Java.

What is a Class?

A class in Java is a user-defined data type that serves as a blueprint for creating objects. It defines the attributes (data fields) and behaviors (methods) that the objects created from the class can possess.

Key Points:

  • A class is a blueprint for objects.
  • It defines attributes and methods.
  • Objects are instances of a class.

Syntax of a Class

The basic syntax to define a class in Java is as follows:

class ClassName {
    // Attributes (data fields)
    dataType attributeName;

    // Constructor
    public ClassName(parameters) {
        // Initialize attributes
    }

    // Methods
    returnType methodName(parameters) {
        // Method body
    }
}

Example: Defining and Using a Class

Let's consider a real-world example: a Car class. We will define a Car class with attributes such as color, model, and speed, and methods such as start(), accelerate(), and brake(). Then, we will create an instance of the Car class and use it.

Step 1: Define the Car Class

public class Car {
    // Attributes (state)
    private String color;
    private String model;
    private int speed;

    // Constructor
    public Car(String color, String model) {
        this.color = color;
        this.model = model;
        this.speed = 0; // Initially, the car is stationary
    }

    // Methods (behavior)
    public void start() {
        System.out.println(model + " is starting.");
        speed = 10; // Starting speed
    }

    public void accelerate(int increment) {
        speed += increment;
        System.out.println(model + " is accelerating. Speed: " + speed + " km/h");
    }

    public void brake() {
        speed = 0;
        System.out.println(model + " has stopped.");
    }

    // Getters
    public String getColor() {
        return color;
    }

    public String getModel() {
        return model;
    }

    public int getSpeed() {
        return speed;
    }
}

Step 2: Create and Use an Instance of the Car Class

public class Main {
    public static void main(String[] args) {
        // Creating an object of the Car class
        Car myCar = new Car("Red", "Toyota Corolla");

        // Using the object
        myCar.start();
        myCar.accelerate(20);
        myCar.brake();

        // Accessing the object's attributes
        System.out.println("Car Model: " + myCar.getModel());
        System.out.println("Car Color: " + myCar.getColor());
        System.out.println("Car Speed: " + myCar.getSpeed() + " km/h");
    }
}

Explanation:

  1. Defining the Car Class:

    • The Car class has three attributes: color, model, and speed.
    • It has a constructor to initialize the color and model attributes, and the speed is initially set to 0.
    • The class has three methods: start(), accelerate(int increment), and brake(), representing the behavior of the car.
    • The class also includes getter methods to access the attributes of the car.
  2. Creating and Using an Object:

    • In the Main class, we create an instance of the Car class using the new keyword.
    • We then call the methods start(), accelerate(int increment), and brake() on the myCar object to simulate the car's behavior.
    • We access the attributes of the myCar object using the getter methods and print their values.

Text-based Diagram

Class: Car
+---------------------------+
|         Car               |
+---------------------------+
| - color: String           |
| - model: String           |
| - speed: int              |
+---------------------------+
| + Car(color, model)       |
| + start(): void           |
| + accelerate(int): void   |
| + brake(): void           |
| + getColor(): String      |
| + getModel(): String      |
| + getSpeed(): int         |
+---------------------------+

Object: myCar
+---------------------------+
|         myCar             |
+---------------------------+
| - color: "Red"            |
| - model: "Toyota Corolla" |
| - speed: 0                |
+---------------------------+
| + start()                 |
| + accelerate(int)         |
| + brake()                 |
| + getColor()              |
| + getModel()              |
| + getSpeed()              |
+---------------------------+

Conclusion

In Java, a class is a blueprint for creating objects. It defines the attributes and methods that the objects created from the class can possess. By using classes and objects, we can model real-world entities and their interactions, making our code more modular, reusable, and maintainable.

Comments