what is class in java with example

what is class in java with example

1 year ago 34
Nature

In Java, a class is a blueprint or template from which individual objects are created. A class contains fields (variables) and methods (functions) that define the behavior and properties of objects created from it. Here is an example of a class in Java:

public class Car {
    String make;
    String model;
    int year;

    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    public void start() {
        System.out.println("The " + year + " " + make + " " + model + " is starting.");
    }

    public void stop() {
        System.out.println("The " + year + " " + make + " " + model + " is stopping.");
    }
}

In this example, the Car class has three fields: make, model, and year. It also has two methods: start() and stop(), which define the behavior of a Car object.

To create an object from a class, we use the new keyword followed by the class name and any necessary arguments for the constructor. Here is an example of creating a Car object:

Car myCar = new Car("Toyota", "Camry", 2022);

This creates a new Car object with the make "Toyota", model "Camry", and year 2022, and assigns it to the variable myCar. We can then call methods on the myCar object, such as:

myCar.start();

This would output "The 2022 Toyota Camry is starting." to the console.

Read Entire Article