🚀 Understanding Liskov Substitution Principle (LSP) with a Simple Java Example One of the most misunderstood SOLID principles is the Liskov Substitution Principle (LSP). 📌 Definition: Subclasses should be replaceable for their base class without altering the correctness of the program. 💻 Example: class Notification { public void sendnot(){ System.out.println("Welcome to the takeUforward"); } } class TextNot extends Notification { public void sendnot() { System.out.println("Welcome to the takeUforward java course"); } } class WhatsAppNot extends Notification { public void sendnot() { System.out.println("Welcome to the takeUforward DSA course"); } } public class TufNot { public static void main(String[] args) { Notification nt = new TextNot(); nt.sendnot(); } } ✅ Why this follows LSP: TextNot and WhatsAppNot can fully replace Notification No unexpected behavior is introduced The program works correctly regardless of which subclass is used ❌ When LSP is violated: If a subclass breaks expected behavior, like: class SilentNotification extends Notification { public void sendnot() { throw new UnsupportedOperationException(); } } Now substituting this class breaks the system 🚨 🧠 Key Insight: Inheritance is not just about reusing code — it's about preserving behavior. 🔥 Takeaway: Always design subclasses so that they extend behavior, not break it. #Java #OOP #SOLID #LSP #SystemDesign #Programming Raj Vikramaditya i understand topic
Liskov Substitution Principle in Java with Notification Example
More Relevant Posts
-
🚀 Day 6 of my Java journey — Exception Handling, Threads + DSA Practice! Today I went deep into error handling and multithreading in Java! 🔥 ⚠️ Exception Handling ✅ Exception = unexpected error at runtime (file not found, null pointer, etc.) ✅ throw — manually throw an exception in your code ✅ throws — declare that a method might throw an exception ✅ try-catch-finally — handle exceptions gracefully 🐛 Types of Errors in Java ✅ Compile-time error — syntax mistakes (missing semicolon, wrong type) ✅ Runtime error — happens while running (divide by zero, null pointer) ✅ Logical error — code runs but gives wrong answer (hardest to find!) 🧵 Threads in Java ✅ Thread = a separate path of execution inside your program ✅ Multithreading = running multiple threads at the same time ✅ Extends Thread class OR implements Runnable interface ✅ Used in real applications for performance and speed! 💻 DSA Practice — GeeksForGeeks ✅ Solved: Print array in Pendulum Arrangement ✅ Logic: Sort array → place minimum in center → fill alternately right and left ✅ Input: {1, 3, 2, 5, 4} → Output: {5, 3, 1, 2, 4} Practicing DSA daily alongside Java concepts — because knowing syntax is not enough, problem solving is what gets the perfection ! Day 1 ✅ | Day 2 ✅ | Day 3 ✅ | Day 4 ✅ | Day 5 ✅ | Day 6 .... #Java #JavaDeveloper #ExceptionHandling #Multithreading #DSA #GeeksForGeeks #100DaysOfCode #BackendDevelopment #TechCareer #LearningToCode #ProblemSolving
To view or add a comment, sign in
-
Deep Dive into Core Java Concepts 🚀 Today, I explored some important Java concepts including toString(), static members, and method behavior in inheritance. 🔹 The toString() method (from Object class) is used to represent an object in a readable format. By default, it returns "ClassName@hashcode", but by overriding it, we can display meaningful information. 🔹 Understanding static in Java: ✔️ Static variables and methods are inherited ❌ Static methods cannot be overridden ✔️ Static methods can be hidden (method hiding) 🔹 What is Method Hiding? If a subclass defines a static method with the same name and parameters as the parent class, it is called method hiding, not overriding. 🔹 Key Difference: ➡️ Overriding → applies to instance methods (runtime polymorphism) ➡️ Method Hiding → applies to static methods (compile-time behavior) 🔹 Also revised execution flow: ➡️ Static blocks (Parent → Child) ➡️ Instance blocks (Parent → Child) ➡️ Constructors (Parent → Child) This learning helped me clearly understand how Java handles inheritance, memory, and method behavior internally. Continuing to strengthen my Core Java fundamentals 💻🔥 #Java #OOP #CoreJava #Programming #LearningJourney #Coding
To view or add a comment, sign in
-
-
Day 11/100 – Java Practice Challenge 🚀 Continuing my #100DaysOfCode journey with another important Java concept. 🔹 Topic Covered: Compile-time vs Runtime Polymorphism 💻 Practice Code: 🔸 Compile-time Polymorphism (Method Overloading) class Calculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } 🔸 Runtime Polymorphism (Method Overriding) class Animal { void sound() { System.out.println("Animal sound"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { // Compile-time Calculator c = new Calculator(); System.out.println(c.add(10, 20)); System.out.println(c.add(10, 20, 30)); // Runtime Animal a = new Cat(); a.sound(); } } 📌 Key Learnings: ✔️ Compile-time → method decided at compile time ✔️ Runtime → method decided at runtime ✔️ Overloading vs Overriding difference 🎯 Focus: Understanding how Java resolves method calls 🔥 Interview Insight: Difference between compile-time and runtime polymorphism is one of the most frequently asked Java interview questions. #Java #100DaysOfCode #MethodOverloading #MethodOverriding #Polymorphism #JavaDeveloper #Programming #LearningInPublic
To view or add a comment, sign in
-
Q. Can an Interface Extend a Class in Java? This is a common confusion among developers and even I revisited this concept deeply today. - The answer is NO, an interface cannot extend a class. - It can only extend another interface. But there is something interesting: - Even though an interface doesn’t extend Object, all public methods of the Object class are implicitly available inside every interface. Methods like: • toString() • hashCode() • equals() These are treated as abstractly redeclared in every interface. ⚡ Why does Java do this? - To support upcasting and polymorphism, ensuring that any object referenced via an interface can still access these fundamental methods. ❗ Important Rule: While you can declare these methods in an interface, you cannot provide default implementations for them. interface Alpha { default String toString() { // ❌ Compile time error return "Hello"; } } Reason? Because these methods already have implementations in the Object class. Since every class implicitly extends Object, allowing default implementations of these methods in interfaces would create ambiguity during method resolution. Therefore, Java does not allow interfaces to provide default implementations for Object methods. 📌 Interfaces don’t extend Object, but its public methods are implicitly available. However, default implementations for them are not allowed. #Java #OOP #InterviewPreparation #Programming #Developers #Learning #SoftwareEngineering
To view or add a comment, sign in
-
Method Overloading : Method Overloading in Java allows a class to have multiple methods with the same name but different parameters, enabling compile-time polymorphism. Methods can share the same name if their parameter lists differ. Cannot overload by return type alone; parameters must differ. The compiler chooses the most specific match when multiple methods could apply. The different ways of method overloading in Java are mentioned below: 1. Changing the Number of Parameters : Method overloading can be achieved by changing the number of parameters when passing to different methods. 🚀Explanation: 👉🏻Two methods have the same name but different number of parameters. 👉🏻Compiler selects the correct method based on how many arguments are passed. 2. Changing Data Types of Parameters : In many cases, methods can be considered overloaded if they have the same name but have different parameter types, methods are considered to be overloaded. 🚀Explanation: 👉🏻Methods differ in parameter types (int vs double). 👉🏻Compiler matches the method based on the exact data type of arguments. 3. Changing the Order of Parameters : Method overloading can also be implemented by rearranging the parameters of two or more overloaded methods. 🚀Explanation: 👉🏻Methods have the same name but parameter order is different. 👉🏻Compiler identifies which method to call based on sequence of arguments. #AnandKumarBuddarapu #core java #method overloading
To view or add a comment, sign in
-
💻 Understanding Buffer Problem & Wrapper Classes in Java While working with Java input using scanner, many beginners face a tricky issue called the Buffer Problem when using Scanner. What happens? --->>When you use nextInt() or nextFloat(), it reads only the number and leaves the newline (\n) in the buffer. --->>So the next nextLine() gets skipped unexpectedly! ~Quick Fix: Always clear the buffer: int n = scan.nextInt(); scan.nextLine(); // clear buffer String name = scan.nextLine(); 🔄 Wrapper Classes in Java Java provides Wrapper Classes to convert primitive data types into objects. @Examples: int → Integer float → Float char → Character #These are super useful when: ✔ Converting String → primitive ✔ Working with collections (like ArrayList) ✔ Using built-in utility methods 🌍 Real-Time Example Imagine a job application system: User input: 101,John,50000 **To process this** 👇 String[] data = input.split(","); int id = Integer.parseInt(data[0]); String name = data[1]; int salary = Integer.parseInt(data[2]); Here, Wrapper Classes help convert text into usable data types. #Key Takeaways ✔ Always clear buffer when mixing nextInt() & nextLine() ✔ Wrapper classes make data conversion easy ✔ Essential for real-world input handling & backend systems #Mastering these small concepts builds a strong foundation in Java! TAP Academy #Java #Programming #OOP #JavaDeveloper #Coding #SoftwareDevelopment #LearnJava
To view or add a comment, sign in
-
-
♻️ Ever wondered how Java manages memory automatically? Java uses Garbage Collection (GC) to clean up unused objects — so developers don’t have to manually manage memory. Here’s the core idea in simple terms 👇 🧠 Java works on reachability It starts from GC Roots: • Variables in use • Static data • Running threads Then checks: ✅ Reachable → stays in memory ❌ Not reachable → gets removed 💡 Even objects referencing each other can be cleaned if nothing is using them. 🔍 Different types of Garbage Collectors in Java: 1️⃣ Serial GC • Single-threaded • Best for small applications 2️⃣ Parallel GC • Uses multiple threads • Focuses on high throughput 3️⃣ CMS (Concurrent Mark Sweep) • Runs alongside application • Reduces pause time (now deprecated) 4️⃣ G1 (Garbage First) • Splits heap into regions • Balanced performance + low pause time 5️⃣ ZGC • Ultra-low latency GC • Designed for large-scale applications ⚠️ One important thing: If an object is still referenced (even accidentally), it won’t be cleaned → which can lead to memory issues. 📌 In short: Java automatically removes unused objects by checking whether they are still reachable — using different GC strategies optimized for performance and latency. #Java #Programming #JVM #GarbageCollection #SoftwareDevelopment #TechConcepts
To view or add a comment, sign in
-
-
The Diamond Problem in Java occurs in languages that allow multiple inheritance, where a class inherits from two classes that share a common superclass. This situation leads to ambiguity when both parent classes define the same method, raising the question of which method should be used. Java circumvents this issue by not supporting multiple inheritance with classes. However, a similar problem can arise with interfaces and default methods. Consider the following example: interface A { default void show() { System.out.println("A"); } } interface B { default void show() { System.out.println("B"); } } class Test implements A, B { public static void main(String[] args) { Test t = new Test(); t.show(); // This results in a compilation error } } In this case, since both interfaces provide the same method, Java requires the class to override it explicitly. Here’s how to resolve it with specific interface calls: class Test implements A, B { public void show() { A.super.show(); // Calls method from interface A B.super.show(); // Calls method from interface B } } This approach allows for explicit selection or combination of behavior from both interfaces. #Java #OOP #InterviewQuestions #BackendDevelopment #Programming
To view or add a comment, sign in
-
-
ArrayDeque in Java Collections Continuing my deep dive into the Java Collections Framework, today I explored ArrayDeque, a powerful class for efficient data manipulation. 🔹 What is ArrayDeque? ArrayDeque is a class that implements the Deque (Double-Ended Queue) interface. It allows insertion and deletion from both ends (front & rear). 🔹 Key Characteristics Does not support indexing → no get(index) methods Default capacity → 16 Resizing → capacity grows as current × 2 Maintains insertion order Allows duplicates Allows heterogeneous data ❌ Does not allow null values 👉 Why null is not allowed? Because methods like poll() and peek() return null when the deque is empty. If null elements were allowed, Java wouldn’t be able to differentiate between: “No element” “Actual null value” 🔹 Constructors ArrayDeque() → default ArrayDeque(int capacity) → custom size ArrayDeque(Collection c) → from another collection 🔹 Hierarchy ArrayDeque → Deque → Queue → Collection → Iterable 🔹 Important Methods addFirst(), addLast() removeFirst(), removeLast() peek(), poll() offer(), offerFirst(), offerLast() 🔹 Traversal forEach() Iterator → forward traversal DescendingIterator → reverse traversal 👉 Traditional for loop & ListIterator not applicable (no indexing) 🔹 Performance Insertion/Deletion (both ends) → O(1) Faster than Stack and LinkedList for queue operations 🔹 When to Use? When you need fast insertion/removal at both ends When indexing is not required Preferred over Stack for stack operations 🔹 Learning Outcome Clear understanding of Deque structure Difference between index-based vs non-index structures Better decision-making for choosing the right collection Grateful to Tap Academy for building strong data structure foundations 🚀 🙌 Special thanks to the amazing trainers at TAP Academy: kshitij kenganavar Sharath R MD SADIQUE Bibek Singh Vamsi yadav Harshit T Ravi Magadum Somanna M G Rohit Ravinder TAP Academy #TapAcademy #Week13Learning #CoreJava #CollectionsFramework #ArrayDeque #DataStructures #JavaFundamentals #LearningByDoing #FullStackJourney #VamsiLearns
To view or add a comment, sign in
-
-
Two Pointer Technique: Today I explored the Two Pointer approach in Java, and it completely changed how I look at array problems 👇 🔹 Instead of using nested loops (O(n²)), we can solve many problems in O(n) using two pointers. 💡 Basic Idea: - Use two pointers (left & right) - Move them based on conditions - Reduce unnecessary iterations 📌 Example: Move Zeroes - Keep a slow pointer for non-zero elements - Traverse with a fast pointer - Swap when needed This simple technique makes code more efficient and clean 🔥 Still learning, but improving step by step 💪 👉 What other problems can be solved using two pointers? Today I practiced the Two Pointer approach in Java using the "Move Zeroes" problem 👇 💡 Idea: - Use a slow pointer to track position of non-zero elements - Use a fast pointer to traverse the array - Swap when needed 🧠 Java Code: public class MoveZeroes { public static void moveZeroes(int[] arr) { int slow = 0; for (int fast = 0; fast < arr.length; fast++) { if (arr[fast] != 0) { int temp = arr[slow]; arr[slow] = arr[fast]; arr[fast] = temp; slow++; } } } public static void main(String[] args) { int[] arr = {1, 2, 0, 4, 3, 0, 5, 0}; moveZeroes(arr); for (int num : arr) { System.out.print(num + " "); } } } ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) Small step, but feels great to understand optimization like this 🔥 👉 Any better approaches or suggestions? #Java #DSA #TwoPointers #LearningInPublic #CodingJourney
To view or add a comment, sign in
More from this author
Explore related topics
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