Access Modifier

Package meant folder in java.

Subclass meant all classes implement from parent or super class.

Modifier Same Class Same Package Subclass (diff pkg) Other Packages
public
protected
default
private

Classes & Objects

class Car {
    private String model;
    private int year;

    // Custom Constructor this will override the default one.
    Car(String model, int year) {
        this.model = model;
        this.year = year;
    }

    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;
    }
}

Encapsulation

class BankAccount {
    private double balance; 
    // hidden from outside
		// balance is like a private state vault.
		// If balance were public, any external code could bypass the rules, and the        n the logic of the whole class (getBalance, deposit, withdraw) would be unreliable.
		// With encapsulation it will makes sure all updates happen safely and consistently.
		
    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) balance -= amount;
    }
}

2. Inheritance

class Animal {
    void eat() {
        System.out.println("This animal eats food");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();   // inherited from Animal
        d.bark();  // defined in Dog
    }
}