Classes and objects basics

Classes

A class in Java is a blueprint for creating objects. It defines a type by bundling data (fields) and methods that work on the data into a single unit.

Components of a Class:

  1. Fields (Instance Variables): These are variables that hold the state of an object.
  2. Methods: These define the behavior of the objects created from the class.
  3. Constructors: Special methods used to initialize new objects.

Example:

public class Car {
    // Fields
    private String color;
    private String model;
    private int year;

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

    // Methods
    public void displayDetails() {
        System.out.println("Color: " + color);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
    }

    // Getter and Setter methods
    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }
}

Objects

An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created.

Creating Objects:

To create an object, use the new keyword followed by the class constructor.

Example:

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

        // Accessing methods of the object
        myCar.displayDetails();

        // Modifying fields using setter methods
        myCar.setColor("Blue");
        System.out.println("Updated Color: " + myCar.getColor());
    }
}