Skip to content
On this page

Object-Oriented Programming (OOP)

Classes and Objects:

Classes are blueprints for creating objects, which are instances of a class.

java
// Class definition
public class Circle {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double area() {
        return 3.14 * radius * radius;
    }
}

Constructors and this Keyword:

Constructors are special methods used to initialize object properties. The this keyword refers to the current instance of the class.

java
// Constructors and this keyword
public class Person {
    private String name;
    private int age;

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

Inheritance:

Inheritance allows a class to inherit properties and methods from another class.

java
// Inheritance
public class Animal {
    public void speak() {
        System.out.println("Animal sound");
    }
}

public class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("Woof!");
    }
}

Encapsulation and Abstraction:

Encapsulation hides the internal implementation details of an object, and abstraction provides a simplified interface for interacting with the object.

java
// Encapsulation and Abstraction
public class BankAccount {
    private double balance;

    public BankAccount(double balance) {
        this.balance = balance;
    }

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

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

    public double getBalance() {
        return balance;
    }
}

Polymorphism:

Polymorphism allows objects of different classes to be treated as objects of the same class.

java
// Polymorphism
public interface Animal {
    void speak();
}

public class Cat implements Animal {
    @Override
    public void speak() {
        System.out.println("Meow!");
    }
}

public class Duck implements Animal {
    @Override
    public void speak() {
        System.out.println("Quack!");
    }
}

public class Zoo {
    public static void animalSound(Animal animal) {
        animal.speak();
    }
}