Method Overriding in Java — Stop Memorizing, Start Understanding Most beginners think they understand overriding… until polymorphism hits them in an interview. Here’s the reality 👇 🔹 What is Method Overriding? When a subclass changes the behavior of a method already defined in its parent class. 👉 Same method name 👉 Same parameters 👉 Same return type If any of these differ → you're NOT overriding, you're doing something else. --- 🔹 The Core Truth (Most People Miss This) Java doesn’t decide which method to run at compile time. It decides at runtime based on the actual object. Parent obj = new Child(); obj.method(); // Calls Child's method, not Parent's If you don’t understand this line, you don’t understand overriding. --- 🔹 Rules You Should Actually Care About ✔ Static methods → NOT overridden (they are hidden) ✔ Private methods → NOT overridden (not even visible) ✔ Final methods → Cannot be overridden ✔ Use "@Override" → saves you from stupid mistakes --- 🔹 Where Developers Mess Up ❌ Thinking reference type controls execution ❌ Confusing overloading with overriding ❌ Ignoring runtime polymorphism --- 🔹 Real Use Case Instead of writing different method names for every role: Employee e = new Manager(); e.raiseSalary(); Java automatically calls the correct implementation. Clean. Scalable. Maintainable. --- 🔹 Why This Matters If you don’t get overriding: → You won’t understand polymorphism → You’ll struggle with Spring Boot (proxies, beans, etc.) → You’ll fail basic Java interviews 💡 Bottom Line Overriding isn’t theory — it’s the backbone of real-world Java. Master this, or keep writing rigid, beginner-level code. #Java #OOP #Programming #BackendDevelopment #Coding #JavaDeveloper #SoftwareEngineering #InterviewPreparation
Java Method Overriding: Understanding Polymorphism
More Relevant Posts
-
You can write Java code for years… and still not understand OOP. Most developers know: ✔ classes ✔ inheritance ✔ polymorphism ✔ Encapsulation But struggle with: ❌ When to use composition over inheritance ❌ Why equals() & hashCode() break systems ❌ How poor design creates tight coupling ❌ What seniors actually mean by “good design.” After 2+ years in production, I realized this gap. So I stopped memorizing concepts… and started understanding how OOP works in real systems. I went deep, really deep, and created structured notes covering: 🔹 Objects & memory model (Heap vs Stack) 🔹 Constructors, chaining & object lifecycle 🔹 Encapsulation & controlled access 🔹 Inheritance vs Composition (real-world usage) 🔹 Polymorphism — what actually happens at runtime 🔹 Abstract class vs Interface — real design decisions 🔹 SOLID principles with practical scenarios 🔹 Immutability & thread safety 🔹 Inner classes & hidden memory leaks 🔹 Wrapper classes & Integer cache pitfalls 🔹 Enums as powerful classes (not just constants) 🔹 Dependency Injection — from scratch to Spring 🔹 Object class — equals(), hashCode(), clone() The biggest realization: OOP is not about syntax. It’s about designing systems that don’t break at scale. This is Part 02 of my Java Interview Prep series (Part 01 was JVM Internals - find the post link in comments ) If you're preparing for Java interviews, struggling with low-level design, or want to think like a senior engineer, this is for you. #Java #OOP #InterviewPrep #SoftwareEngineering #BackendDevelopment #JavaDeveloper #SystemDesign #LearningInPublic #SpringBoot #CleanCode
To view or add a comment, sign in
-
⏳ Day 15 – 1 Minute Java Clarity – static Keyword in Java One keyword… but it changes everything! ⚡ 📌 What is static? When something is static, it belongs to the CLASS — not to any object. 👉 All objects share the same static member. 📌 Static Variable: class Student { String name; static String school = "Java Academy"; } 👉 Every student object shares the same school name. ✔ Memory created only ONCE in Method Area. 📌 Static Method: class MathUtils { static int square(int n) { return n * n; } } MathUtils.square(5); // No object needed! ⚠️ Static methods CANNOT access non-static variables directly. ⚠️ this keyword is NOT allowed inside static methods. 📌 Static Block: static { System.out.println("Runs before main()!"); } 👉 Executes ONCE when class loads — even before main() runs! ✔ Used for one-time setup like DB config loading. 💡 Real-time Example: Think of a company: Every employee has their own name → non-static But company name is the same for all → static ✅ ⚠️ Interview Trap: Why is main() static? 👉 JVM calls main() without creating any object. If main() wasn't static — who would create the object first? 🤔 💡 Quick Summary ✔ static = belongs to class, not object ✔ Static block runs before main() ✔ Static methods can't use this or non-static members 🔹 Next Topic → final keyword in Java Did you know static block runs before main()? Drop 🔥 if this was new! #Java #JavaProgramming #StaticKeyword #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
🌟 Hello Shining Stars!!! 🙏 💡 Java Type Promotion Hierarchy (Must-Know for Developers) Understanding type promotion is key to avoiding subtle bugs in Java 👇 🔼 Hierarchy (Widening Conversion): byte → short → int → long → float → double char → int → long → float → double ⚡ Golden Rules: 👉 byte, short, and char are automatically promoted to int in expressions 👉 Result = largest data type in the expression 👉 ✅ Promotion (widening) is automatic 👉 ❌ De-promotion (narrowing) is NOT automatic — requires explicit casting 🚨 Edge Case Examples (Tricky but Important): byte a = 10; byte b = 20; byte c = a + b; // ❌ Compilation Error // a + b becomes int → cannot store in byte without casting int x = 130; byte b = (byte) x; // ⚠️ Explicit cast (data loss) // Output will be -126 due to overflow char ch = 'A'; System.out.println(ch + 1); // Output: 66 // 'A' → 65 → promoted to int 🧠 Method vs Constructor Promotion (Important Interview Point): void test(int x) { System.out.println("int method"); } void test(double x) { System.out.println("double method"); } test(10); // Calls int method (exact match preferred over promotion) 👉 In methods, Java allows type promotion during overload resolution 👉 But constructors don’t “prefer” promotion the same way — exact match is prioritized, and ambiguous cases can lead to compilation errors 🎯 Takeaway: Java silently promotes smaller types, but it never automatically demotes them — and overload resolution can surprise you! #Java #Programming #Developers #Coding #InterviewPrep #TechTips 👍 Like | 🔁 Repost | 🔄 Share | 💬 Comment | 🔔 Follow | 🤝 Connect to grow together
To view or add a comment, sign in
-
🚀 Do you really know the order in which Java executes your code? Most developers write code… But fewer truly understand how Java executes it behind the scenes. Let’s break one of the most asked (and misunderstood) concepts 👇 🧠 Java Execution Order (Class → Object) Whenever a class is used and an object is created, Java follows this strict order: 👉 Step 1: Static Phase (Runs only once) - Static variables - Static blocks ➡ Executed top to bottom 👉 Step 2: Instance Phase (Runs every time you create an object) - Instance variables - Instance blocks ➡ Executed top to bottom 👉 Step 3: Constructor - Finally, the constructor is executed --- 🔥 Final Order (Must Remember) ✔ Static Variables ✔ Static Blocks ✔ Instance Variables ✔ Instance Blocks ✔ Constructor --- 🧩 Example class Demo { static int a = print("Static A"); static { print("Static Block"); } int x = print("Instance X"); { print("Instance Block"); } Demo() { print("Constructor"); } static int print(String msg) { System.out.println(msg); return 0; } public static void main(String[] args) { new Demo(); } } 💡 Output: Static A Static Block Instance X Instance Block Constructor --- ⚠️ Pro Tips 🔹 Static runs only once per class 🔹 Instance logic runs for every object 🔹 In inheritance: - Parent → Child (Static) - Parent → Constructor → Child (Instance) --- 🎯 Why this matters? Understanding this helps you: ✔ Debug tricky initialization issues ✔ Write predictable code ✔ Perform better in interviews --- 💬 Next time you write a class, ask yourself: “What runs first?” #Java #JavaInternals #Programming #Developers #CodingInterview #TechLearning
To view or add a comment, sign in
-
-
💡 Final vs Immutable in Java – Why You Can’t Convert a Final Variable to Immutable Ever got confused when asked in interviews: If I declare a StringBuffer as final, does it become immutable Here’s the truth 1️⃣ final is about the variable reference You cannot reassign the variable But you can modify the object it points to Example: final StringBuffer sb = new StringBuffer("Java") sb.append(" Easy") System.out.println(sb) // Output → Java Easy ✅ Even though sb is final, we can append/change content ❌ But if we try sb = new StringBuffer("is") → compilation error 2️⃣ immutable is about the object itself Its state cannot be changed once created Example: String → String s = "Java"; s.concat(" Easy"); → original s is still "Java" 💡 Analogy: Think of final as locking the address of a house – you cannot move to a new house, but you can renovate inside freely Immutable is like a museum – nothing inside can ever change ⚡ Key takeaway for interviews → Declaring a variable final does not make the object immutable ✨ Keep coding, keep experimenting, your next aha moment is just one line of code away #Java #JavaTips #CodingLife #Programming #SoftwareDevelopment #LearnJava #Immutable #Final #CareerGrowth #DeveloperTips #TechInterview
To view or add a comment, sign in
-
Java 17+ Interview Question 🔥 | Sealed Interfaces Explained Imagine you have a Payment interface implemented by UPIPayment and CardPayment. Everything is fine until another developer adds a CashPayment class that also implements it — but your client doesn’t want that. How do you restrict which classes can implement the Payment interface? Before Java 17, there was no clean way to enforce this. Solution: Use the sealed keyword (introduced in Java 17) with the permits clause. ————————— sealed interface Payment permits UPIPayment, CardPayment { } final class UPIPayment implements Payment { } final class CardPayment implements Payment { } // This will now give a compilation error // class CashPayment implements Payment { } —————————- Key Rules: • Only the classes listed in permits can implement the sealed interface. • Every implementing class must be explicitly marked as: • final → cannot be extended further • sealed → can define its own permitted subclasses • non-sealed → can be freely extended You can also combine this with records (which are implicitly final). This feature gives you full control over the inheritance hierarchy at compile time — no more unexpected implementations in large codebases. What would you choose for UPIPayment — final, sealed, or non-sealed? And why does a record work without explicitly adding final? Drop your thoughts in the comments 👇 #Java #Java17 #SealedInterfaces #JavaInterviewQuestions #BackendDevelopment #ProgrammingTips #AI #ML
To view or add a comment, sign in
-
-
🚀 𝐒𝐡𝐚𝐫𝐩𝐞𝐧 𝐘𝐨𝐮𝐫 𝐉𝐚𝐯𝐚 𝐒𝐤𝐢𝐥𝐥𝐬: 𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠 & 𝐌𝐮𝐥𝐭𝐢𝐭𝐡𝐫𝐞𝐚𝐝𝐢𝐧𝐠 Preparing for interviews or brushing up on core concepts? I’ve put together a set of thought‑provoking questions on 𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠 and 𝐌𝐮𝐥𝐭𝐢𝐭𝐡𝐫𝐞𝐚𝐝𝐢𝐧𝐠 in Java to help you test your knowledge. 👉 These aren’t just textbook definitions—they’re practical scenarios that every Java developer should be comfortable with. ⚡𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠 𝐢𝐧 𝐉𝐚𝐯𝐚 1.What is the difference between checked and unchecked exceptions in Java? Can you give examples of each? 2.Why is it generally discouraged to catch the Exception class directly? 3.What happens if an exception is thrown inside a finally block? 4. How does the throw keyword differ from throws in Java? 5.Can a try block exist without a catch block? If yes, under what condition? 6.What is the role of 𝐜𝐮𝐬𝐭𝐨𝐦 𝐞𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧𝐬? When should you create one? How does exception propagation work in Java, and how can you control it? What is the difference between 𝐑𝐮𝐧𝐭𝐢𝐦𝐞𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 and 𝐄𝐫𝐫𝐨𝐫? 🔀 𝐌𝐮𝐥𝐭𝐢𝐭𝐡𝐫𝐞𝐚𝐝𝐢𝐧𝐠 𝐢𝐧 𝐉𝐚𝐯𝐚 1.What is the difference between 𝐩𝐫𝐨𝐜𝐞𝐬𝐬𝐞𝐬 and 𝐭𝐡𝐫𝐞𝐚𝐝𝐬 in Java? 2. How does the 𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐢𝐳𝐞𝐝 keyword help in thread safety? 3.What is the difference between 𝐬𝐥𝐞𝐞𝐩() 𝐚𝐧𝐝 𝐰𝐚𝐢𝐭() methods? 4.Can you explain the difference between 𝐓𝐡𝐫𝐞𝐚𝐝 𝐜𝐥𝐚𝐬𝐬 and 𝐑𝐮𝐧𝐧𝐚𝐛𝐥𝐞 𝐢𝐧𝐭𝐞𝐫𝐟𝐚𝐜𝐞? 5.What is a 𝐝𝐞𝐚𝐝𝐥𝐨𝐜𝐤? How can you prevent it? 6. How does the 𝐄𝐱𝐞𝐜𝐮𝐭𝐨𝐫 𝐟𝐫𝐚𝐦𝐞𝐰𝐨𝐫𝐤 improve thread management compared to manually creating threads? 7.What is the difference between 𝐜𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭 𝐜𝐨𝐥𝐥𝐞𝐜𝐭𝐢𝐨𝐧𝐬(like ConcurrentHashMap) and normal collections? 8. How does the volatile keyword differ from synchronized in terms of thread safety?
To view or add a comment, sign in
-
📌 Method References in Java — Cleaner Than Lambdas Method references provide a concise way to refer to existing methods using lambda-like syntax. They improve readability when a lambda simply calls an existing method. 1️⃣ What Is a Method Reference? Instead of writing a lambda: x -> System.out.println(x) We can write: System.out::println --- 2️⃣ Syntax ClassName::methodName Used when: • Lambda just calls an existing method • No additional logic is required --- 3️⃣ Types of Method References 🔹 Static Method Reference ClassName::staticMethod Example: Integer::parseInt --- 🔹 Instance Method Reference (of object) object::instanceMethod Example: System.out::println --- 🔹 Instance Method Reference (of class) ClassName::instanceMethod Example: String::length --- 🔹 Constructor Reference ClassName::new Example: ArrayList::new --- 4️⃣ Example Comparison Using Lambda: list.forEach(x -> System.out.println(x)); Using Method Reference: list.forEach(System.out::println); --- 5️⃣ Benefits ✔ More readable code ✔ Less boilerplate ✔ Cleaner functional style ✔ Works seamlessly with Streams --- 🧠 Key Takeaway Method references are a shorthand for lambda expressions that call existing methods. Use them when they improve clarity, not just to shorten code. #Java #Java8 #MethodReference #FunctionalProgramming #BackendDevelopment
To view or add a comment, sign in
-
🚀 How does filter() work internally in Java Streams? (Deep Dive) Most Asked Interview Question. Most developers use filter() daily… but very few understand what actually happens under the hood. Let’s break it down 👇 🔍 1. filter() is an Intermediate Operation filter() doesn’t process data immediately. It returns a new Stream with a pipeline stage attached. 👉 This means: No iteration happens yet No elements are checked yet It just builds a processing chain ⚙️ 2. Functional Interface Behind It Internally, filter() takes a Predicate: boolean test(T t); For every element, this predicate decides: ✔️ Keep → pass to next stage ❌ Reject → drop immediately 🔗 3. Pipeline Chaining (Lazy Execution) list.stream() .filter(x -> x > 10) .map(x -> x * 2) .collect(...) 👉 Internally, Java builds a linked pipeline of operations: Source → Filter → Map → Terminal Each element flows one-by-one, not step-by-step. 🔥 4. Element-wise Processing (Not Batch Processing) Instead of: ❌ Filtering all → then mapping Java does: ✔️ Take one element ✔️ Apply filter ✔️ If passed → apply map ✔️ Move to next This is called vertical processing (fusion of operations). ⚡ 5. Internal Iteration (Not External Loops) Unlike traditional loops: for(int x : list) Streams use internal iteration, controlled by the JVM. 👉 This enables: Better optimization Parallel execution Cleaner code 🧠 6. Lazy + Short-Circuiting Optimization filter() works with terminal operations like: findFirst() anyMatch() 👉 Processing stops as soon as the result is found. 🚀 7. Behind the Scenes (Simplified Flow) Stream → Spliterator → Pipeline Stages → Terminal Operation Spliterator → Breaks data into chunks Sink Chain → Passes elements through operations Terminal Op → Triggers execution 💡 Key Insight filter() is not just a condition checker. It is: ✔️ Lazy ✔️ Functional ✔️ Pipeline-based ✔️ Optimized for performance 🎯 Interview One-Liner 👉 "filter() is a lazy intermediate operation that uses a Predicate to process elements through a pipeline with internal iteration and operation fusion." #Java #Streams #BackendDevelopment #JavaDeveloper #InterviewPrep #Coding #TechDeepDive
To view or add a comment, sign in
-
-
📘 Ghost Keywords in Java – `goto` and `const` While learning Java fundamentals, I discovered an interesting concept in the language design: ghost keywords. Java reserves two keywords — `goto` and `const` — but surprisingly, they are not actually used in the language. 🔹 What does this mean? A reserved keyword is a word that cannot be used as an identifier (like a variable name, class name, or method name). Even though `goto` and `const` exist in Java’s reserved keyword list, they have no functionality implemented in the language. For example: ```java int goto = 10; // Compile-time error int const = 20; // Compile-time error ``` Even though they do nothing, the Java compiler still prevents developers from using them. 🔹 Why were they reserved? When Java was being designed, its creators intentionally avoided certain features that could lead to poor coding practices. • *goto`– In languages like C and C++, `goto` allows jumping to different parts of a program. However, it often leads to spaghetti code, making programs difficult to read, maintain, and debug. Java avoided this to promote structured programming. • const`– Instead of `const`, Java introduced the `final` keyword to define constants in a cleaner and more object-oriented way. Example: ```java final int MAX_VALUE = 100; ``` 🔹 **Why keep them reserved?** Keeping these keywords reserved helps prevent naming conflicts and allows flexibility for future language design decisions. 💡 Key takeaway: Sometimes what a programming language chooses not to include* is just as important as what it includes. #Java #Programming #SoftwareDevelopment #ComputerScience #Coding #LearnInPublic
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development