people often say that 𝐦𝐞𝐭𝐡𝐨𝐝 𝐨𝐯𝐞𝐫𝐫𝐢𝐝𝐢𝐧𝐠 𝐢𝐬 𝐫𝐮𝐧𝐭𝐢𝐦𝐞 𝐩𝐨𝐥𝐲𝐦𝐨𝐫𝐩𝐡𝐢𝐬𝐦 but that statement isn’t entirely accurate with c++ 𝗺𝗲𝘁𝗵𝗼𝗱 𝗼𝘃𝗲𝗿𝗿𝗶𝗱𝗶𝗻𝗴 simply means a child class provides its own implementation of a function that already exists in the parent class with the same signature, however, runtime polymorphism only happens when the method call is resolved based on the actual object type at runtime in c++(my fav), this only happens if the base class function is marked 𝐯𝐢𝐫𝐭𝐮𝐚𝐥 and the call is made through a 𝐛𝐚𝐬𝐞 𝐜𝐥𝐚𝐬𝐬 𝐩𝐨𝐢𝐧𝐭𝐞𝐫 𝐨𝐫 𝐫𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞 𝘦.𝘨. 𝘉𝘢𝘴𝘦* 𝘱𝘵𝘳 = 𝘯𝘦𝘸 𝘋𝘦𝘳𝘪𝘷𝘦𝘥(); 𝘱𝘵𝘳->𝘥𝘪𝘴𝘱𝘭𝘢𝘺(); without virtual, the call is resolved at compile time, even if the object is actually 𝘋𝘦𝘳𝘪𝘷𝘦𝘥 but wow (𝘢𝘯𝘰𝘵𝘩𝘦𝘳 𝘳𝘦𝘢𝘴𝘰𝘯 𝘯𝘰𝘵 𝘵𝘰 𝘩𝘢𝘵𝘦 𝘫𝘢𝘷𝘢), 𝐦𝐞𝐭𝐡𝐨𝐝𝐬 𝐚𝐫𝐞 𝐯𝐢𝐫𝐭𝐮𝐚𝐥 𝐛𝐲 𝐝𝐞𝐟𝐚𝐮𝐥𝐭 in java (except static, final, and private), when a method is overridden, runtime polymorphism happens automatically :) java performs 𝐝𝐲𝐧𝐚𝐦𝐢𝐜 𝐝𝐢𝐬𝐩𝐚𝐭𝐜𝐡 𝐚𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜𝐚𝐥𝐥𝐲, without needing a virtual keyword #CPP #Java #OOP #SystemDesign #Programming
C++ vs Java: Method Overriding and Runtime Polymorphism
More Relevant Posts
-
🚀 LeetCode Day 18 – Complement of Base 10 Integer Today I solved LeetCode Problem 1009: Complement of Base 10 Integer using Java. 🧠 Problem: Given a non-negative integer n, return the complement of its binary representation. The complement means flipping all bits in the binary form of the number. 📌 Example: Input: n = 5 Binary of 5 → 101 Complement → 010 Output → 2 💡 Approach: • Create a bitmask with all bits set to 1 up to the highest bit of n. • Use the XOR (^) operator with the mask to flip the bits. 💻 Java Code: class Solution { public int bitwiseComplement(int n) { if (n == 0) return 1; int mask = 0, temp = n; while (temp > 0) { mask = (mask << 1) | 1; temp >>= 1; } return n ^ mask; } } ⏱️ Time Complexity: O(log n) 📦 Space Complexity: O(1) 📚 Practicing Data Structures & Algorithms daily to improve problem-solving skills. #LeetCode #Java #DSA #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 98 - #100DaysOfCode Today’s problem was all about string comparison and operations simulation in Java. 💡 Problem Insight: Given a list of operations like "++X", "X++", "--X", "X--", we need to compute the final value of X after performing all operations. ⚠️ One key learning today: In Java, always use .equals() for string comparison instead of ==. Using == compares references, not actual content — a very common mistake! 🧠 Approach: Initialize x = 0 Traverse through each operation Increment or decrement based on the operation string 📌 What I Improved Today: Better understanding of string handling in Java Avoiding common pitfalls in comparisons Writing cleaner conditional logic #Java #CodingJourney #LeetCode #100DaysOfCode #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
As part of JDK26, the JEP500 makes the final fields (specifically instance final fields) of the class effectively immutable, meaning any mutations via deep reflection API embodied in the setAccessible and set methods of the java.lang.reflect.Field class will now issues a warning. WARNING: Final field f in p.C has been [mutated/unreflected for mutation] by class com.foo.Bar.caller in module N (file:/path/to/foo.jar) WARNING: Use --enable-final-field-mutation=N to avoid a warning WARNING: Mutating final fields will be blocked in a future release unless final field mutation is enabled But why? 1. Provide Integrity by Default 2. Enable JIT Constant folding optimizations Historically the JDK releases are preparing for restrictions of deep reflection via, 1. introduced hidden classes in JDK 15 and record classes in JDK 16. 2. strongly encapsulated JDK internals in JDK 17. 3. JDK 24, started the process to remove methods in sun.misc.Unsafe that, like deep reflection, allow the mutation of final fields. How to identify? When JFR is enabled, the JVM records a jdk.FinalFieldMutation event whenever code mutates a final instance field or uses Lookup.unreflectSetter to get a MethodHandle with write access to a reflected final field. And, 1. Serialization libraries should use sun.reflect.ReflectionFactory 2. Libraries should not use deep reflection to mutate final fields 3. Cloning should not use deep reflection https://lnkd.in/gjgznVaw
To view or add a comment, sign in
-
🚀 Day 97 of My 100 Days LeetCode Challenge | Java Today’s problem was a solid exercise in matrix processing and prefix sum optimization. The goal was to count the number of submatrices whose sum is less than or equal to a given value (k). A brute-force approach would be too slow, so the key was to use 2D prefix sums to efficiently compute submatrix sums. By converting the matrix into a prefix sum matrix, we can calculate the sum of any submatrix in constant time, making the overall solution much more efficient. ✅ Problem Solved: Count Submatrices With Sum ≤ K ✔️ All test cases passed (859/859) ⏱️ Runtime: 7 ms 🧠 Approach: 2D Prefix Sum 🧩 Key Learnings: ● Prefix sums are powerful for optimizing repeated range sum queries. ● 2D prefix sums extend the same idea from arrays to matrices. ● Preprocessing can drastically reduce computation time. ● Avoiding brute force is key in large input problems. ● Matrix problems often become easier with the right transformation. This problem reinforced how preprocessing techniques like prefix sums can turn complex problems into efficient solutions. 🔥 Day 97 complete — sharpening matrix optimization and prefix sum skills. #LeetCode #100DaysOfCode #Java #PrefixSum #Matrix #Algorithms #ProblemSolving #DSA #CodingJourney #Consistency
To view or add a comment, sign in
-
-
Refactoring for Clarity: Array Manipulation in Java 👨💻 I’ve just finished a practical exercise on array manipulation. While the goal was simple (summing two arrays), I used it as an opportunity to apply improvements. - Method decomposition: Separated concerns into specialized methods (Read, Calculate, Display). - Input validation: Built a robust loop to handle invalid inputs and prevent crashes. - Data Formatting: Used printf to create a clear, readable results table. Small improvements in logic and organization make a huge difference in software quality. #Java #Algorithms #CleanCode #Backend #LearningToCode
To view or add a comment, sign in
-
-
Interfaces also allow a class to follow multiple contracts at the same time. Unlike classes, where a class can extend only one parent class, a class in Java can implement multiple interfaces. Things that became clear : • a class can implement more than one interface • each interface can define a different set of behaviours • the implementing class must provide implementations for all the methods • this approach allows combining different capabilities in a single class • it helps achieve flexibility while avoiding multiple inheritance of classes A simple example shows how multiple interfaces can be implemented : interface ICalculator { void add(int a, int b); void sub(int a, int b); } interface IAdvancedCalculator { void mul(int a, int b); void div(int a, int b); } class CalculatorImpl implements ICalculator, IAdvancedCalculator { public void add(int a, int b) { System.out.println(a + b); } public void sub(int a, int b) { System.out.println(a - b); } public void mul(int a, int b) { System.out.println(a * b); } public void div(int a, int b) { System.out.println(a / b); } } This structure allows the class to support operations defined by multiple interfaces while keeping responsibilities organized. #java #oop #programming #learning #dsajourney
To view or add a comment, sign in
-
LeetCode Problem || Find Unique Binary String (1980)🚀 Today I solved the problem "Find Unique Binary String" using Java. 🔹 Problem: We are given an array of n binary strings, each of length n. The goal is to return a binary string of length n that does not exist in the array. 🔹 Approach (Diagonal Flip Technique): The idea is simple but powerful: Traverse the array using index i. Look at the i-th character of the i-th string (nums[i][i]). Flip the bit (0 → 1, 1 → 0). Append it to a result string. 💡 Time Complexity: O(n) Practicing problems like this strengthens logical thinking and problem-solving skills. #LeetCode #Java #CodingPractice #ProblemSolving #DSA
To view or add a comment, sign in
-
-
Day 66 of #100DaysOfLeetCode 💻✅ Solved #3427. Sum of Variable Length Subarrays problem in Java. Approach: • Iterated through each index of the array • Determined the starting index using i - nums[i] • Ensured the start index does not go below 0 • Calculated sum of elements from start to current index i • Added each subarray sum to the total Performance: ✓ Runtime: 1 ms (Beats 99.90% submissions) ✓ Memory: 45.22 MB (Beats 56.30% submissions) Key Learning: ✓ Practiced handling variable-length subarrays ✓ Improved understanding of index-based range calculations ✓ Strengthened nested loop logic for array problems Learning one problem every single day 🚀 #Java #LeetCode #DSA #Arrays #PrefixSum #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
I just shipped CodeDebug CLI : an AI-powered production debugger that runs entirely in your terminal. Built in pure Java 17 (sorry for Java 21/25 lovers). 𝗛𝗼𝘄 𝗶𝘁 𝘄𝗼𝗿𝗸𝘀 : $ tail -n 200 app.log | cdb → Pipes your log into Claude AI → Auto-detects Java / Python / Kotlin / Go / TypeScript / Rust → Returns: ROOT CAUSE · FIX · WHY · PREVENT → With severity labels: [CRITICAL] [HIGH] [MEDIUM] [LOW] 𝗪𝗵𝗮𝘁 𝗺𝗮𝗸𝗲𝘀 𝗶𝘁 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁: ✦ Single fat JAR : just java -jar and run ✦ Zero HTTP dependencies : uses Java 17's built-in HttpClient ✦ JLine3 REPL with arrow-key history and Ctrl+C support ✦ Config persisted to ~/.codedebugrc ✦ Token usage tracked per session ✦ Extending to a new language = 1 enum constant, 0 other changes 𝗖𝗼𝘀𝘁: ~$0.001 per debug session. Less than $1/month of heavy use. Wrote a full technical breakdown on Medium covering the architecture, the zero-deps HTTP client design, and how language auto-detection works. - Full article in the comments - GitHub: https://lnkd.in/enY2c6er #Java #CLI #DevTools #Anthropic #AI #OpenSource
To view or add a comment, sign in
-
💡 Java isn’t as simple as “new Object() = heap memory” Most developers learn: 👉 new Object() → Heap allocation 👉 Reference → Stack ✔️ Good for basics… but not the full story. 🚀 What really happens in modern Java? With JIT (Just-In-Time Compiler), the JVM can optimize away object creation completely. Yes, you read that right. void process() { Object obj = new Object(); System.out.println(obj.hashCode()); } 👉 If obj is used only inside the method and doesn’t “escape” ➡️ JVM may: Skip heap allocation ❌ Allocate on stack ⚡ Or eliminate the object entirely 🔥 🧠 The core concept: Escape Analysis If an object: ❌ Does NOT leave the method → Optimized ✅ Escapes (returned, shared, stored) → Heap allocation ⚠️ Common misconception ❌ “Avoid creating objects to save memory” ✔️ Reality: JVM is smarter than that Premature optimization can: Make code ugly Reduce maintainability Give no real performance gain 🔧 Static vs Object? ✔️ Use static when no state is needed ✔️ Use objects when behavior depends on data 👉 It’s not about avoiding new 👉 It’s about writing clean, logical design 🏁 Final takeaway Java is not just compiled — it adapts at runtime 🔥 The JVM decides: What to allocate What to remove What to optimize 👨💻 Write clean code. 📊 Measure performance. ⚡ Trust the JVM. #Java #JVM #Performance #Backend #SoftwareEngineering #CleanCode
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