What are the OOP concepts in Java?
"The core OOP concepts in Java are built on four main pillars:
-
Encapsulation: The mechanism of bundling data (variables) and the methods (functions) that operate on that data into a single unit, called a class. It also involves restricting direct access to some of an object's components, which is achieved using access modifiers like
privateand publicgetter/settermethods. -
Inheritance: The mechanism where one class (a child or subclass) acquires the properties and behaviors of another class (a parent or superclass). This promotes code reusability and establishes an "is-a" relationship. In Java, this is done using the
extendskeyword. -
Polymorphism: The ability of an object to take many forms. It allows us to perform a single action in different ways. The most common form is method overriding, where a child class provides a specific implementation of a method already defined in its parent class.
-
Abstraction: The concept of hiding complex implementation details and showing only the essential features to the user. This is achieved in Java using abstract classes (with the
abstractkeyword) and interfaces."
Detailed Concepts for Better Understanding
This section dives into each concept with examples, keywords, and the "why" behind them.
1. Encapsulation (The Protector)
- Core Idea: "Bind data with the code that manipulates it, and protect it from outside interference and misuse."
- How it's done:
- Declare class variables as
private. - Provide public
getterandsettermethods to view and/or modify the variable values.
- Declare class variables as
- Why it's important:
- Data Hiding: The internal state of the object is hidden from the outside world.
- Control & Validation: You can add logic inside setters to validate data before assigning it. For example, ensuring an age is not negative.
- Flexibility & Maintainability: You can change the internal implementation of a class without affecting the code that uses it.
Example:
public class BankAccount {
// Data is declared private
private double balance;
private String accountNumber;
// Public getter and setter methods to control access
public double getBalance() {
// Could add authentication logic here
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount; // Validation logic
}
}
// No direct setter for 'balance', protecting it from arbitrary changes
}
2. Inheritance (The Reuser)
- Core Idea: "Create new classes based on existing classes, inheriting their fields and methods to promote code reuse."
- How it's done: Using the
extendskeyword in Java. - Why it's important:
- Code Reusability: Write a general class once and extend it for more specific cases.
- Method Overriding: Enables polymorphism (see next point).
- Establishes a Relationship: Creates a logical "is-a" hierarchy (e.g., a
Caris-aVehicle).
Example:
// Superclass (Parent)
class Vehicle {
String brand;
void start() {
System.out.println("Vehicle is starting...");
}
}
// Subclass (Child) - inherits from Vehicle
class Car extends Vehicle { // 'extends' is the keyword
int numberOfDoors;
@Override
void start() {
System.out.println("Car is starting with a key...");
}
}
// Car now has 'brand', 'numberOfDoors', and both the original and overridden 'start()' method.
3. Polymorphism (The Shape-Shifter)
- Core Idea: "One interface, multiple implementations." The same action can be performed in different ways.
- How it's done:
- Method Overriding (Runtime Polymorphism): A subclass provides a specific implementation for a method already defined in its superclass. The JVM decides which method to call at runtime based on the actual object type.
- Method Overloading (Compile-Time Polymorphism): Having multiple methods in the same class with the same name but different parameters.
- Why it's important:
- Flexibility & Extensibility: Allows you to write code that works with the general class but behaves differently with specific subclasses.
- Simplifies Code: You can use a parent class reference to call methods that are implemented in various child classes.
Example (Method Overriding):
Vehicle myVehicle = new Car(); // Parent reference, Child object
myVehicle.start(); // Output: "Car is starting with a key..."
myVehicle = new Bike(); // Same reference, different object
myVehicle.start(); // Output: "Bike is starting by pedaling..."
// The JVM calls the correct 'start()' method based on the actual object (Car or Bike).
4. Abstraction (The Simplifier)
- Core Idea: "Hide the implementation details and show only the functionality to the user."
- How it's done:
- Abstract Classes (
abstract): A class that cannot be instantiated. It can contain both abstract methods (without a body) and concrete methods (with a body). It's used when there's a strong "is-a" relationship and some base implementation can be shared. - Interfaces (
interface): A pure abstraction contract (until Java 7). It defines what a class must do, but not how. A classimplementsan interface. From Java 8 onwards, interfaces can havedefaultandstaticmethods with bodies.
- Abstract Classes (
- Why it's important:
- Reduces Complexity: The user doesn't need to know the internal logic, just how to use it.
- Enforces a Contract: Ensures that any class implementing an interface provides implementations for all its methods.
- Achieves Loose Coupling: Code depends on abstractions (interfaces) rather than concrete implementations.
Example (Interface):
// Abstraction - defines the "what"
interface Shape {
double calculateArea(); // No body - just a contract
}
// Concrete implementation - defines the "how"
class Circle implements Shape {
double radius;
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle implements Shape {
double length, width;
@Override
public double calculateArea() {
return length * width;
}
}
// You can use the Shape interface to handle any shape without knowing its specific type.
Bonus: Two Additional Key Concepts
Often, Classes & Objects are mentioned as the foundation upon which these four pillars are built.
- Class: A blueprint or template for creating objects. It defines the attributes (data) and behaviors (methods) that the objects created from it will have.
- Object: An instance of a class. It is a real-world entity (e.g., a specific car, a particular bank account) with actual state and behavior.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
