For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
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.
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:
There are four fundamental pillars that define object-oriented programming. These concepts work together to create robust and maintainable software applications.
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:
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 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 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:
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 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:
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 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 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 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:
NOT OOPs Concepts:
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
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.
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.