DEV Community

silambarasan rajendran
silambarasan rajendran

Posted on

4

day-23: Java OOP Made Easy: final, Inheritance, Polymorphism & Encapsulation

The Ultimate Guide to Java's final Keyword

The final keyword in Java is a powerful modifier that enforces immutability, security, and design control in your code. It can be applied to classes, methods, and variables, each with distinct effects.

Important notes:
"A class declared with the final keyword cannot be extended (no inheritance is allowed from it), but it can still inherit from other classes (unless those parent classes are also final)."

Example for Final varible and Method family analogy:

public class GrandFather {

    public void work() {
        System.out.println("Working");
    }
}
Enter fullscreen mode Exit fullscreen mode

Father class can be inherit from Grandfather class

public /*final*/ class Father extends GrandFather {
    final int amount = 100000; 

    public void get_married() {
        System.out.println("parent conditions");
    }
    public final void go_to_college() {
        System.out.println("Minimum UG Degree");
    }
}
Enter fullscreen mode Exit fullscreen mode

Son can override the father class method called as method overrding:

public class Son extends Father { 
    public static void main(String[] args) {
        Son son = new Son(); 
        System.out.println(son.amount); 
        //son.amount = 1234567;
        son.get_married();  // method overriding
        //son.go_to_college();

        Father father = new Father(); 
        father.get_married();
    }
    //Method Overriding
    public void get_married() {
        System.out.println("Son stand");
    }
}
Enter fullscreen mode Exit fullscreen mode

Why We Need Polymorphism, Encapsulation, and Inheritance (Simple Explanation):

These OOP (Object-Oriented Programming) concepts help make code:
✅ Cleaner (easy to read & maintain)
✅ Reusable (write once, use many times)
✅ Flexible (easy to modify without breaking everything)

1. Inheritance (Parent-Child Relationship)
What?
A class (child) can reuse properties/methods from another class (parent).

Why?
Avoids rewriting the same code ("Don’t Repeat Yourself" principle).
Example:

public /*final*/ class Father extends GrandFather {
    final int amount = 100000; 

    public void get_married() {
        System.out.println("parent conditions");
    }
    public final void go_to_college() {
        System.out.println("Minimum UG Degree");
    }
}
public class Son extends Father { 
    public static void main(String[] args) {
        Son son = new Son(); 
        System.out.println(son.amount); 
        son.get_married();  // method overriding

    }
    //Method Overriding
    public void get_married() {
        System.out.println("Son stand");
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Polymorphism (One Thing, Many Forms)
What?
The same method can behave differently based on the object.

Why?
Lets you write flexible code that works with multiple types.

Example:

public class ITC_Hotel {

    // Single flexible payment method
    public void pay(int amount, String paymentMethod, double discount) {
        double finalAmount = amount;

        if (discount > 0) {
            finalAmount = amount - (amount * discount/100);
            System.out.print("After " + discount + "% discount: ");
        }

        if (paymentMethod != null) {
            System.out.println("Paid ₹" + finalAmount + " using " + paymentMethod);
        }
        else if (amount > 5000) {
            System.out.println("Please pay ₹" + finalAmount + " using Credit Card");
        }
        else {
            System.out.println("Please pay ₹" + finalAmount + " using UPI");
        }
    }

    public static void main(String[] args) {
        ITC_Hotel hotel = new ITC_Hotel();

        // All cases handled by one method:
        hotel.pay(6000, null, 0);    // Recommends CC
        hotel.pay(3000, "UPI", 0);   // Specific payment
        hotel.pay(5000, null, 20.0); // Discounted payment
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Encapsulation (Data Protection)
What?
Hiding internal details (private fields) and exposing only what’s needed (public methods).

Why?
Prevents accidental misuse (e.g., setting negative age).
Example:

class BankAccount {  

    private double balance;  // Hidden  

    public void deposit(double amount) {  
        if (amount > 0) balance += amount;  // Controlled access  
    }  
}  
Enter fullscreen mode Exit fullscreen mode

Real-Life Analogy
Concept Real-Life Example Why It’s Useful
Inheritance Child inheriting parent’s traits (e.g., last name) Saves time (no need to redefine everything)
Polymorphism A "Print" button working differently for Word vs. Excel One interface, multiple behaviors
Encapsulation ATM hiding cash but providing a withdrawal method Security (you can’t directly touch the cash)

Without These?

❌ Messy code (copy-pasting everywhere)
❌ Brittle systems (small changes break everything)
❌ Security risks (data easily corrupted)

OOP = Organized, Safe, and Reusable Code! 🚀

Redis image

Short-term memory for faster
AI agents 🤖💨

AI agents struggle with latency and context switching. Redis fixes it with a fast, in-memory layer for short-term context—plus native support for vectors and semi-structured data to keep real-time workflows on track.

Start building

Top comments (0)

AWS Q Developer image

Build your favorite retro game with Amazon Q Developer CLI in the Challenge & win a T-shirt!

Feeling nostalgic? Build Games Challenge is your chance to recreate your favorite retro arcade style game using Amazon Q Developer’s agentic coding experience in the command line interface, Q Developer CLI.

Participate Now

👋 Kindness is contagious

Delve into a trove of insights in this thoughtful post, celebrated by the welcoming DEV Community. Programmers of every stripe are invited to share their viewpoints and enrich our collective expertise.

A simple “thank you” can brighten someone’s day—drop yours in the comments below!

On DEV, exchanging knowledge lightens our path and forges deeper connections. Found this valuable? A quick note of gratitude to the author can make all the difference.

Get Started