Java Abstraction & Abstract Classes Explained

🚀 Day 40 – Core Java | Abstraction & Abstract Classes Today’s session focused on the fourth pillar of Object-Oriented Programming — Abstraction and how it works in Java. 🔹 What is Abstraction? Abstraction means: 👉 Hiding the implementation details and showing only the essential features. Real-world example When you drive a car: You press the accelerator You use the steering You apply brakes But you don’t know the internal engine mechanism. The internal working is hidden — this is Abstraction. Another example: Using Instagram / WhatsApp You swipe or send a message But you don’t know the internal code. You only see the features, not the implementation. 🔹 Abstract Method in Java An abstract method is an incomplete method. It contains only the method signature, not the body. Example: abstract void calculateArea(); Here: Method name → calculateArea No implementation The implementation will be provided by child classes. 🔹 Abstract Class If a class contains at least one abstract method, the class must be declared as abstract. Example: abstract class Shape { abstract void calculateArea(); } Important rule: 👉 Abstract class cannot be instantiated (object cannot be created). ❌ Not allowed Shape s = new Shape(); Because the class contains incomplete methods. 🔹 Example Used in Class We implemented Shapes example using abstraction. Parent class: Shape Child classes: Square Rectangle Circle Common behavior: acceptInput() calculateArea() displayArea() Design Shape (Abstract Class) abstract class Shape { float area; abstract void acceptInput(); abstract void calculateArea(); void displayArea() { System.out.println(area); } } Child classes override the abstract methods. Example: class Square extends Shape Each class calculates area differently. 🔹 Advantages 1️⃣ Code Reusability Common methods like displayArea() written once in parent class. 2️⃣ Better Design Abstract class defines common structure. 3️⃣ Cleaner Code Child classes implement only required logic. 🔹 Important Rules of Abstraction ✔ Abstract method → no body ✔ Class with abstract method → must be abstract ✔ Abstract class cannot create object ✔ Abstract class can contain normal methods also ✔ Abstract keyword cannot be used with variables ❌ Not allowed abstract int a; 🔹 Abstract vs Final abstract and final cannot be used together. Reason: abstract → method must be overridden final → method cannot be overridden So they contradict each other. 🔹 Key Insight Abstraction works like a hierarchy: Top level → more abstract Lower level → more concrete Example: Bird (abstract) ↓ Eagle (partially abstract) ↓ GoldenEagle / SerpentEagle (concrete) As we move down the hierarchy, abstract behavior becomes fully implemented. #Java #CoreJava #OOPS #Abstraction #AbstractClass #JavaDeveloper #ProgrammingJourney #SoftwareEngineering #LearningInPublic

To view or add a comment, sign in

Explore content categories