Java Classes and Objects

In Java, classes and objects are the fundamental building blocks of object-oriented programming. A class is a blueprint for creating objects, defining their properties (attributes) and behaviors (methods). An object is an instance of a class.

1. Defining a Class

A class is defined using the class keyword followed by the class name and class body enclosed in braces.

public class Car {
    // Attributes
    String brand;
    String model;
    int year;

    // Methods
    public void startEngine() {
        System.out.println("Engine started.");
    }
}

2. Creating Objects

Objects are created using the new keyword, which calls the class constructor.

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.brand = "Toyota";
        myCar.model = "Corolla";
        myCar.year = 2020;
        myCar.startEngine(); // Outputs: Engine started.
    }
}

3. Accessing Attributes and Methods

Use the dot notation to access an object's attributes and methods.

System.out.println(myCar.brand); // Outputs: Toyota
myCar.startEngine();

4. Creating Multiple Objects

You can create multiple objects from the same class, each with its own set of attributes.

Car car1 = new Car();
Car car2 = new Car();
car1.brand = "Honda";
car2.brand = "Ford";

Key Takeaways

  • Classes define the structure and behavior of objects.
  • Objects are instances of classes and represent real-world entities.
  • Understanding classes and objects is essential for object-oriented programming in Java.