Java Object-Oriented Programming (OOP) Concepts and Examples

0 views
10 months ago

Java is a popular programming language known for its strong support for Object-Oriented Programming (OOP). OOP is a programming paradigm that uses objects and classes to model and solve real-world problems. Let's explore some key concepts of Java OOP with examples.

1. Classes and Objects

In Java, a class is a blueprint for creating objects. An object is an instance of a class. Here's an example:

class Car {
    String make;
    String model;
    int year;

    void start() {
        System.out.println("Starting the car.");
    }
}

// Creating an object of the Car class
Car myCar = new Car();
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2023;
myCar.start();
    

2. Encapsulation

Encapsulation is the practice of hiding the internal details of an object and providing a public interface for interaction. This is achieved through access modifiers like private, protected, and public. Here's an example:

class BankAccount {
    private double balance;

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        }
    }

    public double getBalance() {
        return balance;
    }
}

BankAccount myAccount = new BankAccount();
myAccount.deposit(1000);
System.out.println("Balance: $" + myAccount.getBalance());
    

3. Inheritance

Inheritance allows a class (subclass or child class) to inherit properties and behaviors from another class (superclass or parent class). Here's an example:

class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }
}

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

Dog myDog = new Dog();
myDog.eat();
myDog.bark();
    

4. Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It includes method overriding and interfaces. Here's an example:

interface Shape {
    void draw();
}

class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing a circle.");
    }
}

class Square implements Shape {
    public void draw() {
        System.out.println("Drawing a square.");
    }
}

Shape shape1 = new Circle();
Shape shape2 = new Square();
shape1.draw();
shape2.draw();
        

These are just some of the fundamental concepts of Java OOP. Learning and applying these principles will help you write more maintainable and scalable Java code.