Java Interview Prep: Method Overriding, Final Keyword, and Inheritance

🚀 Day 24 – Java Concepts for Interviews Method Overriding | Final Keyword | Method Hiding 🔹 1️⃣ Class Terminology In Java inheritance: Parent class → Superclass / Base class Child class → Subclass / Derived class The relationship is called an “is-a” relationship and is created using the extends keyword. 🔹 2️⃣ Method Overriding – 4 Important Rules Method overriding means a child class inherits a method and changes its implementation. Always use @Override for better readability and compile-time checking. Rule 1 – Access Modifier The child method must have same or higher visibility. Visibility order: private → default → protected → public Example: If parent method is protected, child can use: ✔ protected ✔ public ❌ default ❌ private Rule 2 – Return Type Return type must normally be same as parent method. Rule 3 – Covariant Return Type (JDK 5+) Child method can return a subclass type. Example: class Animal {} class Lion extends Animal {} class Base { Animal display() { return new Animal(); } } class Derived extends Base { @Override Lion display() { return new Lion(); } // Valid } ⚠ Works only for objects, not primitives like int, double. Rule 4 – Parameters Parameters must be exactly the same: same number same type same order Only method body changes, not the signature. 🔹 3️⃣ Overriding vs Overloading (Interview Trap) If parent has: display() and child has: display(int a, int b, int c) This is NOT overriding ❌ This is method overloading ✔ Because parameters are different. Using @Override here will give a compile-time error. 🔹 4️⃣ Final Keyword in Java final can be used with variables, methods, and classes. Final Variable Becomes a constant. final float PI = 3.142f; PI = 3.14f; // Error Convention: UPPERCASE_SNAKE_CASE Example: MAX_VALUE, MIN_VALUE Final Method Can be inherited Cannot be overridden Used when behavior must not change in child classes. Final Class A final class cannot be extended. Example: final class Calculator {} class Child extends Calculator {} // Compilation error Examples in Java: String, StringBuilder, StringBuffer, wrapper classes like Integer. 🔹 5️⃣ Static Members and Inheritance Static Variables If child declares the same variable → Variable Hiding Static Methods Static methods cannot be overridden. If same method exists in child → Method Hiding Example: class Parent { static void display() { System.out.println("Parent"); } } class Child extends Parent { static void display() { System.out.println("Child"); // Method hiding } } Using @Override here → ❌ Compilation error #Java #JavaProgramming #OOP #MethodOverriding #MethodOverloading #FinalKeyword #JavaInterviewQuestions #CodingInterview #SoftwareEngineering #LearnJava #100DaysOfCode #Day24

  • timeline

To view or add a comment, sign in

Explore content categories