Java Intermediate Day 1: Object-Oriented Programming Deep Dive

Goal of this Day

Today you will learn:

By the end, you will understand how to design clean and structured Java classes.

Step 1: Classes and Objects (Review)

A class is a blueprint for creating objects.

An object is an instance of a class.


class Person {
    String name;
    int age;
}

Step 2: Constructors

A constructor is used to initialize objects.


public Person(String name, int age) {
    this.name = name;
    this.age = age;
}

Explanation:

Step 3: The this Keyword

this refers to the current object.

It is used to distinguish between class variables and parameters.


this.name = name;

Step 4: Encapsulation

Encapsulation means hiding data and controlling access.


private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

Practice


class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void display() {
        System.out.println(name + " is " + age + " years old.");
    }
}

Exercise

Create a class Car with attributes and methods.

Steps:

Example:


public class Car {
    private String brand;
    private int speed;

    public Car(String brand, int speed) {
        this.brand = brand;
        this.speed = speed;
    }

    public void accelerate() {
        speed += 10;
        System.out.println("Speed increased to " + speed);
    }

    public void brake() {
        speed -= 10;
        System.out.println("Speed decreased to " + speed);
    }

    public static void main(String[] args) {
        Car myCar = new Car("BMW", 50);

        myCar.accelerate();
        myCar.brake();
    }
}