image

OOPs Concepts with Examples in Java

Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of objects. It provides a way to model real-world entities and their interactions within a software system. Java is a widely used object-oriented programming language that fully embraces and implements OOP principles. This article will explore the four fundamental OOP concepts and their implementation in Java, accompanied by examples.

1. Encapsulation

Encapsulation is the bundling of data and methods that operate on that data within a single unit, known as a class. It promotes data hiding and ensures that an object's internal state is accessible and adaptable only through its methods, thereby protecting its integrity.

Example:

public class BankAccount {

    private double balance; // data hiding

    public void deposit(double amount) {

        balance += amount;

    }

    public void withdraw(double amount) {

        if (balance >= amount) {

            balance -= amount;

        } else {

            System.out.println("Insufficient funds.");

        }

    }

    public double getBalance() {

        return balance;

    }

}

In this example, the BankAccount class encapsulates the balance data member and provides controlled access to it through the deposit(), withdraw(), and getBalance() methods.

2. Inheritance

Inheritance is a mechanism that allows a new class (derived or child class) to be based on an existing class (base or parent class). The derived class inherits properties and behaviors from the base class, enabling code reuse and the creation of hierarchical relationships between classes.

Example:

class Vehicle {

    protected int maxSpeed;

    public void start() {

        System.out.println("Vehicle started.");

    }

}

class Car extends Vehicle {

    public void accelerate() {

        System.out.println("Car accelerating to " + maxSpeed + " km/h.");

    }

}

In this example, the Car class inherits from the Vehicle class, obtaining access to the maxSpeed member variable and the start() method. The Car class can also introduce new members and methods, such as the accelerate() method.

3. Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables code flexibility and extensibility by providing a consistent interface for different object types. Polymorphism is achieved through method overriding and method overloading in Java.

Example:

class Animal {

    public void makeSound() {

        System.out.println("The animal makes a sound.");

    }

}

class Dog extends Animal {

    @Override

    public void makeSound() {

        System.out.println("Woof!");

    }

}

class Cat extends Animal {

    @Override

    public void makeSound() {

        System.out.println("Meow!");

    }

}

In this example, the Dog and Cat classes override the makeSound() method inherited from the Animal class, exhibiting method overriding polymorphism. When the makeSound() method is called on an Animal object, the appropriate implementation (based on the actual object type) will be invoked at runtime.

4. Abstraction

Abstraction is the process of hiding unnecessary implementation details and exposing only the essential features of an object or system. In Java, abstraction is achieved through abstract classes and interfaces.

Example:

abstract class Shape {

    abstract double area();

    public void displayInfo() {

        System.out.println("Area: " + area());

    }

}

class Circle extends Shape {

    private double radius;

    Circle(double radius) {

        this.radius = radius;

    }

    @Override

    double area() {

        return Math.PI * radius * radius;

    }

}

In this example, the Shape class is an abstract class that defines an abstract area() method and a concrete displayInfo() method. The Circle class extends Shape and implements the area() method specific to circles. Abstraction allows for the separation of the "what" (the abstract shape concept) from the "how" (the specific area calculation for circles).

FAQs

Here are some frequently asked questions about OOP concepts in Java:

Q1: What is the difference between method overloading and method overriding?

Method overloading is a form of polymorphism that allows a class to have multiple methods with the same name but different parameter lists (different number of parameters, different types of parameters, or both). Method overriding, on the other hand, is a way for a subclass to provide its own implementation of a method that is already defined in its superclass.

Q2: Can you have multiple inheritance in Java?

No, Java does not support multiple inheritance of classes. A class in Java can extend only one parent class. However, Java supports multiple inheritance through interfaces, where a class can implement multiple interfaces.

Q3: What is the purpose of the super keyword in Java?

The super keyword in Java refers to the superclass members (fields or methods) and invokes the superclass constructor. It is commonly used when a subclass needs to access or modify the behavior of its superclass.

Q4: Can you create an instance of an abstract class in Java?

No, you cannot create an instance of an abstract class in Java. Abstract classes are designed to be extended by other classes and serve as a blueprint or base for creating more specific subclasses.

Q5: What is the difference between an abstract class and an interface in Java?

An abstract class is a class that cannot be instantiated and may contain both abstract and concrete methods. It can also have instance variables and constructor implementations. On the other hand, an interface is a pure abstraction that defines a contract, or a set of methods that implementing classes must provide. Interfaces cannot have instance variables or constructors, and all methods in an interface are implicitly abstract.

Share On