what is class in oop java

what is class in oop in java with example

In Java, a class is a blueprint or a template for creating objects. It defines a data structure along with methods that operate on the data. Objects are instances of classes, and they encapsulate data and behavior. Each object created from a class can have its own unique data, but it follows the structure and behavior defined by the class.

Let’s consider a real-life example to illustrate the concept of a class in Java:

Example: 'Car' Class
Example
// Defining a Car class
public class Car {
    // Fields (attributes)
    String brand;
    String model;
    int year;
    double price;

    // Constructor
    public Car(String brand, String model, int year, double price) {
        this.brand = brand;
        this.model = model;
        this.year = year;
        this.price = price;
    }

    // Method to display information about the car
    public void displayInfo() {
        System.out.println("Brand: " + brand);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
        System.out.println("Price: $" + price);
    }

    // Method to start the car
    public void start() {
        System.out.println("The " + brand + " " + model + " is starting.");
    }

    // Method to accelerate the car
    public void accelerate() {
        System.out.println("The " + brand + " " + model + " is accelerating.");
    }

    // Method to stop the car
    public void stop() {
        System.out.println("The " + brand + " " + model + " has stopped.");
    }
}

Now, you can create instances of the Car class and use its methods to perform actions on individual cars:

Example
public class Main {
    public static void main(String[] args) {
        // Creating instances of the Car class
        Car car1 = new Car("Toyota", "Camry", 2022, 25000.50);
        Car car2 = new Car("Honda", "Civic", 2021, 22000.75);

        // Using methods to interact with the cars
        car1.displayInfo();
        car1.start();
        car1.accelerate();
        car1.stop();

        System.out.println(); // Separating output for clarity

        car2.displayInfo();
        car2.start();
        car2.accelerate();
        car2.stop();
    }
}

In this example, the Car class defines the attributes of a car (brand, model, year, price) and methods that represent actions a car can take (display information, start, accelerate, stop). The main method in the Main class demonstrates creating instances of the Car class and using its methods to perform actions on specific cars.

Leave a Reply

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