View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

OOPs Concepts in Java: Principles, Features, and Implementation

Updated on 30/05/20254,575 Views

Object-Oriented Programming (OOP) is the foundation of Java programming language. OOPs concepts in Java help developers create modular and reusable code. Java is completely built around these object-oriented principles.`

What is OOPs in Java? It's a programming approach that organizes code into objects and classes. These objects interact with each other to perform various tasks. This methodology makes Java programs more organized and maintainable. Java implements four core OOPs concepts: encapsulation, inheritance, polymorphism, and abstraction. Each concept serves a specific purpose in software development.

Understanding these principles is crucial for any Java developer. Modern software development relies heavily on OOPs principles for creating scalable applications. Many professionals enhance their skills through online Software Engineering courses. These courses cover advanced OOPs concepts in Java with examples and practical implementations.

What is OOPs in Java

OOPs stands for Object-Oriented Programming System. It's a programming paradigm that uses objects and classes to structure code. Java is inherently object-oriented, making it perfect for implementing OOPs concepts.

The core idea behind OOPs is to model real-world entities as objects. Each object has properties (attributes) and behaviors (methods). This approach mirrors how we think about real-world problems. Java's design philosophy centers around "everything is an object." Even basic operations in Java involve objects and classes. This fundamental approach makes Java a pure object-oriented programming language.

OOPs concept in Java differs from procedural programming in several ways. Procedural programming focuses on functions and procedures. Object-oriented programming emphasizes objects and their interactions.

Unlock a high-paying career with the following full-stack development courses: 

Core OOPs Concepts in Java

There are four fundamental pillars that define object-oriented programming. These concepts work together to create robust and maintainable software applications.

Encapsulation in Java

Encapsulation is the practice of bundling data and methods within a single unit. It restricts direct access to object data from outside the class. This concept provides data security and privacy.

In Java, encapsulation is achieved using access modifiers like private, protected, and public. Private variables can only be accessed through public getter and setter methods. This controlled access prevents unauthorized data modification.

Must read: What is Encapsulation in OOPS? Types, Examples, Implementation, & More

Benefits of Encapsulation:

  • Data hiding and security
  • Controlled access to class members
  • Easier maintenance and debugging
  • Flexibility in changing the implementation

Example of Encapsulation:

public class Student {
    private String name;
    private int age;
    
    // Getter method
    public String getName() {
        return name;
    }
    
    // Setter method
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        if(age > 0) {
            this.age = age;
        }
    }
}

// Main class to test encapsulation
public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("Jiya");
        student.setAge(20);
        
        System.out.println("Name: " + student.getName());
        System.out.println("Age: " + student.getAge());
    }
}

Output:

Name: Jiya

Age: 20

Also explore: Understanding the Difference Between Abstraction and Encapsulation

Inheritance in Java

Inheritance in Java allows a class to acquire properties and methods from another class. The class that inherits is called a child or subclass. The class being inherited from is called parent or superclass.

Java supports single inheritance, meaning a class can extend only one parent class. However, Java supports multiple inheritance through interfaces. This design prevents complexity and ambiguity issues.

Types of Inheritance in Java:

Example of Inheritance:

// Parent class
class Animal {
    protected String name;
    
    public void eat() {
        System.out.println("Animal is eating");
    }
    
    public void sleep() {
        System.out.println("Animal is sleeping");
    }
}

// Child class
class Dog extends Animal {
    public void bark() {
        System.out.println("Dog is barking");
    }
    
    public void displayInfo() {
        System.out.println("This is a dog named " + name);
    }
}

// Main class to test inheritance
public class InheritanceExample {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.name = "Buddy";
        dog.eat();      // Inherited method
        dog.sleep();    // Inherited method
        dog.bark();     // Own method
        dog.displayInfo();
    }
}

Output:

Animal is eating

Animal is sleeping

Dog is barking

This is a dog named Buddy

Check out: What are the Types of Inheritance in Java?

Polymorphism in Java

Polymorphism means "many forms" and allows objects to behave differently based on context. It enables a single interface to represent different underlying forms. Java implements polymorphism through method overloading and method overriding.

Method Overloading occurs when multiple methods have the same name but different parameters. Method Overriding happens when a subclass provides a specific implementation of a parent class method.

Types of Polymorphism:

  • Compile-time Polymorphism (Method Overloading)
  • Runtime Polymorphism (Method Overriding)

Example of Polymorphism:

class Shape {
    public void draw() {
        System.out.println("Drawing a shape");
    }
    
    public void area() {
        System.out.println("Calculating area of shape");
    }
}

class Circle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
    
    @Override
    public void area() {
        System.out.println("Area of circle: π * r * r");
    }
}

class Rectangle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
    
    @Override
    public void area() {
        System.out.println("Area of rectangle: length * width");
    }
}

// Main class to demonstrate polymorphism
public class PolymorphismExample {
    public static void main(String[] args) {
        Shape shape1 = new Circle();
        Shape shape2 = new Rectangle();
        
        shape1.draw();
        shape1.area();
        
        shape2.draw();
        shape2.area();
    }
}

Output:

Drawing a circle

Area of circle: π * r * r

Drawing a rectangle

Area of rectangle: length * width

Must check: Difference Between Overloading and Overriding in Java

Abstraction in Java

Abstraction hides implementation details while showing only essential features to users. It focuses on what an object does rather than how it does it. Java implements abstraction through abstract classes and interfaces.

Abstract classes cannot be instantiated directly and may contain abstract methods. Interfaces define contracts that implementing classes must follow. Both mechanisms help achieve abstraction in Java.

Ways to Achieve Abstraction:

  • Abstract Classes (0-100% abstraction)
  • Interfaces (100% abstraction)

Example of Abstraction:

abstract class Vehicle {
    protected String brand;
    
    // Abstract method
    abstract void start();
    abstract void stop();
    
    // Concrete method
    public void displayBrand() {
        System.out.println("Vehicle brand: " + brand);
    }
}

class Car extends Vehicle {
    public Car(String brand) {
        this.brand = brand;
    }
    
    @Override
    void start() {
        System.out.println("Car engine started with ignition key");
    }
    
    @Override
    void stop() {
        System.out.println("Car stopped by applying brakes");
    }
}

class Bike extends Vehicle {
    public Bike(String brand) {
        this.brand = brand;
    }
    
    @Override
    void start() {
        System.out.println("Bike started with kick start");
    }
    
    @Override
    void stop() {
        System.out.println("Bike stopped by hand brakes");
    }
}

// Main class to test abstraction
public class AbstractionExample {
    public static void main(String[] args) {
        Vehicle car = new Car("Toyota");
        Vehicle bike = new Bike("Honda");
        
        car.displayBrand();
        car.start();
        car.stop();
        
        System.out.println();
        
        bike.displayBrand();
        bike.start();
        bike.stop();
    }
}

Output:

Vehicle brand: Toyota

Car engine started with ignition key

Car stopped by applying brakes


Vehicle brand: Honda

Bike started with kick start

Bike stopped by hand brakes

Also read: Key Differences Between Inheritance and Polymorphism

Features of OOPs in Java

Features of OOPs in Java make it a powerful programming language for software development. These features provide numerous advantages for building complex applications.

Feature

Description

Purpose

Class and Objects

Blueprint and instances

Code organization and reusability

Encapsulation

Data hiding mechanism

Security and controlled access

Inheritance

Code reusability feature

Reduces redundancy and promotes reuse

Polymorphism

Multiple forms behavior

Flexibility and dynamic method binding

Abstraction

Hide implementation details

Simplicity and interface focus

Message Passing

Object communication

Enables object interaction

These features work together to create a robust programming environment. They enable developers to write clean, maintainable, and scalable code.

OOPs Concepts in Java with Examples

OOPs concepts in Java with examples help developers understand practical implementation. Real-world applications demonstrate how these concepts solve programming challenges.

Consider a banking system that uses all four OOPs concepts. Encapsulation protects account balance from direct access. Inheritance creates different account types like savings and checking accounts.

Polymorphism allows different account types to calculate interest differently. Abstraction hides complex transaction processing from users. This combination creates a secure and flexible banking application.

Comprehensive Example - Banking System:

// Abstract class demonstrating abstraction
abstract class BankAccount {
    protected String accountNumber;
    protected double balance;
    protected String customerName;
    
    // Constructor
    public BankAccount(String accountNumber, String customerName, double initialBalance) {
        this.accountNumber = accountNumber;
        this.customerName = customerName;
        this.balance = initialBalance;
    }
    
    // Abstract method - must be implemented by subclasses
    abstract double calculateInterest();
    
    // Concrete methods
    public void deposit(double amount) {
        if(amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        }
    }
    
    public void withdraw(double amount) {
        if(amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount);
        } else {
            System.out.println("Insufficient balance or invalid amount");
        }
    }
    
    // Encapsulation - getter methods
    public double getBalance() {
        return balance;
    }
    
    public String getAccountNumber() {
        return accountNumber;
    }
    
    public String getCustomerName() {
        return customerName;
    }
}

// Inheritance - SavingsAccount extends BankAccount
class SavingsAccount extends BankAccount {
    private double interestRate = 0.04; // 4% interest
    
    public SavingsAccount(String accountNumber, String customerName, double initialBalance) {
        super(accountNumber, customerName, initialBalance);
    }
    
    // Polymorphism - method overriding
    @Override
    double calculateInterest() {
        return balance * interestRate;
    }
    
    public void displayAccountInfo() {
        System.out.println("=== Savings Account Info ===");
        System.out.println("Account Number: " + accountNumber);
        System.out.println("Customer Name: " + customerName);
        System.out.println("Balance: $" + balance);
        System.out.println("Annual Interest: $" + calculateInterest());
    }
}

// Inheritance - CheckingAccount extends BankAccount
class CheckingAccount extends BankAccount {
    private double interestRate = 0.01; // 1% interest
    private double overdraftLimit = 500.0;
    
    public CheckingAccount(String accountNumber, String customerName, double initialBalance) {
        super(accountNumber, customerName, initialBalance);
    }
    
    // Polymorphism - method overriding
    @Override
    double calculateInterest() {
        return balance * interestRate;
    }
    
    // Method overloading - polymorphism
    public void withdraw(double amount, boolean allowOverdraft) {
        if(allowOverdraft && amount <= (balance + overdraftLimit)) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount + " (overdraft used if needed)");
        } else {
            withdraw(amount); // Call parent method
        }
    }
    
    public void displayAccountInfo() {
        System.out.println("=== Checking Account Info ===");
        System.out.println("Account Number: " + accountNumber);
        System.out.println("Customer Name: " + customerName);
        System.out.println("Balance: $" + balance);
        System.out.println("Annual Interest: $" + calculateInterest());
        System.out.println("Overdraft Limit: $" + overdraftLimit);
    }
}

// Main class to demonstrate all OOPs concepts
public class BankingSystemExample {
    public static void main(String[] args) {
        // Creating objects (Instantiation)
        SavingsAccount savings = new SavingsAccount("SAV001", "John Doe", 1000.0);
        CheckingAccount checking = new CheckingAccount("CHK001", "Jane Smith", 500.0);
        
        System.out.println("=== Initial Account States ===");
        savings.displayAccountInfo();
        System.out.println();
        checking.displayAccountInfo();
        
        System.out.println("\n=== Performing Transactions ===");
        
        // Encapsulation in action - using methods to access private data
        savings.deposit(200.0);
        savings.withdraw(150.0);
        
        checking.deposit(300.0);
        checking.withdraw(100.0);
        
        // Polymorphism - method overloading
        checking.withdraw(600.0, true); // Using overdraft
        
        System.out.println("\n=== Final Account States ===");
        savings.displayAccountInfo();
        System.out.println();
        checking.displayAccountInfo();
        
        // Polymorphism - runtime method binding
        System.out.println("\n=== Interest Calculation (Polymorphism) ===");
        BankAccount account1 = savings;  // Upcasting
        BankAccount account2 = checking; // Upcasting
        
        System.out.println("Savings Interest: $" + account1.calculateInterest());
        System.out.println("Checking Interest: $" + account2.calculateInterest());
    }
}

Output:

=== Initial Account States ===

=== Savings Account Info ===

Account Number: SAV001

Customer Name: John Doe

Balance: $1000.0

Annual Interest: $40.0


=== Checking Account Info ===

Account Number: CHK001

Customer Name: Jane Smith

Balance: $500.0

Annual Interest: $5.0

Overdraft Limit: $500.0


=== Performing Transactions ===

Deposited: $200.0

Withdrawn: $150.0

Deposited: $300.0

Withdrawn: $100.0

Withdrawn: $600.0 (overdraft used if needed)


=== Final Account States ===

=== Savings Account Info ===

Account Number: SAV001

Customer Name: John Doe

Balance: $1050.0

Annual Interest: $42.0


=== Checking Account Info ===

Account Number: CHK001

Customer Name: Jane Smith

Balance: $100.0

Annual Interest: $1.0

Overdraft Limit: $500.0


=== Interest Calculation (Polymorphism) ===

Savings Interest: $42.0

Checking Interest: $1.0

This comprehensive example demonstrates all four OOPs concepts working together. Encapsulation protects account data through private variables and public methods. Inheritance allows creating specialized account types. Polymorphism enables different behaviors for the same method calls. Abstraction hides complex implementation details from users.

Also explore: Parameterized Constructors in Java

Which of the Following is Not an OOPs Concept

Which of the following is not oops concept in java? This is a common interview question. Understanding what doesn't belong to OOPs helps clarify the boundaries of object-oriented programming.

Core OOPs Concepts:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

NOT OOPs Concepts:

  • Compilation
  • Debugging
  • Variable Declaration
  • Loop Structures
  • Conditional Statements
  • Exception Handling (though used in OOPs, not a core concept)

Procedural programming elements like functions, procedures, and global variables are not OOPs concepts. These belong to different programming paradigms entirely.

Must explore: A Complete Guide to Java Keywords

Advantages of OOPs in Java

OOPs concepts in Java provide numerous benefits for software development. These advantages make Java a preferred choice for enterprise applications.

Key Advantages:

Code Reusability: Inheritance allows developers to reuse existing code efficiently. New classes can extend existing functionality without rewriting code. This reduces development time and maintenance costs significantly.

Modularity: Classes and objects create modular code structures that are easier to manage. Each module can be developed and tested independently. This approach improves code organization and team collaboration.

Data Security: Encapsulation provides robust data protection mechanisms through access modifiers. Private data cannot be accessed directly from outside classes. This prevents unauthorized data manipulation and ensures system integrity.

Easy Maintenance: OOPs structure makes code easier to modify and maintain over time. Changes in one class don't affect other unrelated classes. This isolation reduces the risk of introducing bugs during updates.

Scalability: Object-oriented design supports building large-scale applications effectively. New features can be added without disrupting existing functionality. This flexibility enables applications to grow with business requirements.

Conclusion

OOPs concepts in Java form the backbone of modern software development practices. These four fundamental principles enable developers to create robust and maintainable applications. Understanding encapsulation, inheritance, polymorphism, and abstraction is essential for Java programming success.

What is OOPs in Java becomes clear through practical implementation and real-world examples. These concepts work together to provide code reusability, security, and flexibility. Mastering OOPs concepts in Java with examples prepares developers for advanced programming challenges and career growth opportunities. Go & learn OOPs concepts in Java now!

FAQs

1. What is OOPs in Java?

OOPs stands for Object-Oriented Programming System, a programming paradigm based on objects and classes. It organizes code into reusable and maintainable structures that model real-world entities. Java is inherently object-oriented, making it ideal for implementing OOPs principles effectively. This approach promotes better code organization, reduces complexity, and enables developers to build scalable enterprise applications with improved maintainability.

2. What are the four main OOPs concepts in Java?

The four core OOPs concepts are encapsulation, inheritance, polymorphism, and abstraction. Each concept serves a specific purpose in creating well-structured and maintainable code. These principles work together to provide the foundation of object-oriented programming in Java. Mastering these concepts is essential for writing professional Java applications and succeeding in technical interviews for software development positions.

3. What is encapsulation in Java with example?

Encapsulation is the bundling of data and methods within a class while restricting direct access to internal data. It uses access modifiers like private, protected, and public to control data visibility. This concept ensures data security and provides controlled access through getter and setter methods. Encapsulation also enables data validation, where setter methods can include logic to validate input before modifying object state.

4. How does inheritance work in Java?

Inheritance allows a class to acquire properties and methods from another class using the 'extends' keyword. The child class inherits all non-private members of the parent class automatically. This mechanism promotes code reusability and establishes hierarchical relationships between classes. Java supports single inheritance to avoid complexity, but multiple inheritance can be achieved through interfaces for flexible design patterns.

5. What is polymorphism in Java?

Polymorphism means "many forms" and allows objects to behave differently based on their actual type. It includes method overloading (compile-time) and method overriding (runtime) implementations. This concept enables a single interface to represent different underlying data types. Polymorphism is crucial for writing flexible code that can work with objects of different types through a common interface.

6. How is abstraction achieved in Java?

Abstraction is achieved through abstract classes and interfaces that hide implementation details from users. Abstract classes can contain both abstract and concrete methods for partial abstraction. Interfaces provide complete abstraction by defining contracts that implementing classes must follow. This concept simplifies complex systems by focusing on what objects do rather than how they do it internally.

7. What is the difference between class and object in Java?

A class is a blueprint or template that defines the structure and behavior of objects. An object is an instance of a class that exists in memory with actual values. Multiple objects can be created from a single class, each with its own state. Understanding this distinction is fundamental to object-oriented programming and helps developers design better software architectures.

8. Can we override private methods in Java?

No, private methods cannot be overridden because they are not visible to subclasses. Private methods have class-level scope and cannot be accessed outside their defining class. However, you can create a method with the same name in the subclass (method hiding). This design ensures encapsulation and prevents unintended modifications to private implementation details in inheritance hierarchies.

9. What is method overloading in Java?

Method overloading allows multiple methods with the same name but different parameter lists within a class. The compiler determines which method to call based on the number and types of arguments. This is an example of compile-time polymorphism in Java programming. Method overloading improves code readability and provides flexibility in method usage with different parameter combinations.

10. What is the 'super' keyword in Java?

The 'super' keyword refers to the immediate parent class object and is used to access parent class members. It can call parent class constructors, methods, and variables from the child class. This keyword is essential for proper inheritance implementation and avoiding naming conflicts. The 'super' keyword also enables proper constructor chaining, ensuring parent class initialization before child class construction.

11. What is an abstract class in Java?

An abstract class is a class that cannot be instantiated and may contain abstract methods without implementation. It can also contain concrete methods with full implementations for shared functionality. Abstract classes provide partial abstraction and serve as base classes for inheritance hierarchies. They are ideal when you need to share common code among related classes while enforcing certain methods to be implemented.

12. What is an interface in Java?

An interface is a contract that defines method signatures without providing implementation details. All methods in an interface are implicitly public and abstract (before Java 8). Interfaces achieve 100% abstraction and support multiple inheritance through implementation by classes. Modern Java versions allow default and static methods in interfaces, providing more flexibility in API design and evolution.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.