In Java, a class is a blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that objects of that type will have. Here's a basic example of a Java class:
Example of a simple class in Java:
public class Car { // Attributes String brand; String color; int year; // Constructor public Car(String brand, String color, int year) { this.brand = brand; this.color = color; this.year = year; } // Method public void drive() { System.out.println("The " + color + " " + year + " " + brand + " is driving."); } }
Example of creating objects in Java:
public class Main { public static void main(String[] args) { // Creating objects of class Car Car car1 = new Car("Toyota", "Blue", 2020); Car car2 = new Car("BMW", "Red", 2019); // Accessing object methods car1.drive(); // Output: The Blue 2020 Toyota is driving. car2.drive(); // Output: The Red 2019 BMW is driving. } }
In this example, Car
is a class with attributes like brand
, color
, and year
, and a method drive()
. car1
and car2
are objects (instances) of the Car
class, each with its own set of attribute values.