Brushing up my OOPS concepts today and revisited an interesting point about 'Runtime Polymorphism' and 'Inheritance concept' in Java. In runtime polymorphism, the JVM decides which overridden method to execute during runtime based on the actual object being created, not the reference type. This usually happens when: - A child class inherits from a parent class - The child overrides a method from the parent class - A parent reference variable refers to a child class object Example: Parent ref = new Child(); Here, the overridden method in the Child class will be executed, even though the reference type is Parent. However, things work differently with variables. If both parent and child classes define a variable with the same name and type, the variable accessed depends on the reference type, not the object type. This is because variables do not participate in runtime polymorphism (they follow variable hiding). For example: class Parent { int a = 10; } class Child extends Parent { int a = 20; } public class Test { public static void main(String[] args) { Parent ref = new Child(); System.out.println(ref.a); } } In this code, the output will be 10, because the reference type is Parent, so it accesses the Parent class variable. This behavior is known as variable hiding. Always interesting to revisit these core concepts — they look simple but have subtle behaviors that are important for writing clean and predictable Java code. #Java #OOPS #Polymorphism #Learning #SoftwareEngineering #SDET #Coding #Inheritance
Java Runtime Polymorphism and Inheritance Concepts
More Relevant Posts
-
Recently, I revised some core Java concepts, and honestly, things started making more sense when I connected them practically. Polymorphism was one of the interesting parts. Method overloading happens at compile time, where the compiler already knows which method to call. But method overriding is different — the JVM decides at runtime, which makes it more dynamic. That’s where I understood the idea of early binding and late binding. Early binding is fixed during compilation, while late binding happens when the program is actually running. Dynamic method dispatch is just this in action — the JVM figuring out which method to execute based on the object. I also revised relationships in OOP. Inheritance follows an “is-a” relationship, like a cargo plane is a plane. Association is more of a “has-a” relationship, and it can be either strong (composition) or loose (aggregation). And one thing that helped me connect everything — Java code first becomes bytecode, and then JVM runs it. That’s where all the runtime decisions happen. Revisiting basics really helps in understanding how things actually work behind the scenes. #Java #OOP #Learning #CodingJourney
To view or add a comment, sign in
-
-
Every time I opened a new Java project in VS Code, I had to set it up from scratch. I work across multiple Java repositories. IntelliJ is my main IDE, but I use VS Code and Cursor for quick navigation and AI-first coding. Lighter. Always ready. But it doesn't pick up IntelliJ configs automatically. So every new project meant: - Mapping source folders manually - Fixing JAR paths - Setting the JDK again Same steps every time. So I tried something different. Instead of writing a script, I wrote a Markdown file. Step-by-step instructions telling the AI exactly what to do. A small snippet from the file: - Check .idea at root only (ignore subdirs) - Extract source roots from .iml files - Map them to java.project.sourcePaths Now I just type /java-vscode-setup in VS Code or Cursor Agent. The AI scans the project. Generates the correct settings.json. Confirms changes before applying them. No scripts. No extra tools. Just clear instructions. This changed how I think about automation. Instead of writing scripts to do the work, you write instructions that guide the AI to do it. Same result. Less hassle. Works across every repo. Could I have done this with a Python script? Yes. But I'm already in Claude or Cursor anyway. So I built it where I work. Still experimenting with this approach. Curious - what task have you turned into a slash command? #AI #Cursor #Claude #VSCode #DevTools
To view or add a comment, sign in
-
Today I learned Polymorphism in Java, one of the core concepts of Object-Oriented Programming (OOP). What is Polymorphism? The word Polymorphism comes from two Greek words: Poly = many Morphs = forms So, Polymorphism means “many forms” — the same parent reference can show different behaviors depending on which child object it refers to. Example: A parent class Plane can behave differently when connected to different child classes: CargoPlane PassengerPlane FighterPlane Plane ref; ref = new CargoPlane(); ref.fly(); ref = new PassengerPlane(); ref.fly(); ref = new FighterPlane(); ref.fly(); Here, the same ref calls fly() but produces different outputs. This is called Runtime Polymorphism (Method Overriding). Tight Coupling When a child class reference directly depends on its own object: CargoPlane cp = new CargoPlane(); cp.fly(); cp.carryCargo(); ✅ Child-specific methods accessible ❌ Less flexible ❌ Harder to extend Loose Coupling When a parent reference points to child objects: Plane ref = new CargoPlane(); ref.fly(); ✅ Flexible ✅ Reusable ✅ Supports polymorphism Advantages of Polymorphism ✅ Code Reusability ✅ Flexibility ✅ Reduction in Complexity Learning these OOP concepts is helping me understand how Java builds scalable and maintainable applications 🚀💻 #Java #Polymorphism #OOP #LooseCoupling #TightCoupling #Programming #SoftwareDevelopment #JavaLearning #CodingJourney
To view or add a comment, sign in
-
-
⏳ Day 21 – 1 Minute Java Clarity – Polymorphism Explained Simply 🎭 Same action… different behaviour! 🔥 📌 What is Polymorphism? 👉 “Poly” = Many 👉 “Morphism” = Forms ✔ One method behaves differently based on the object 👉 It is the core of OOP and makes code flexible & reusable 📌 Types of Polymorphism 1️⃣ Compile-Time Polymorphism 👉 Achieved using Method Overloading class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } ✔ Same method → different parameters ✔ Decided at compile time 2️⃣ Runtime Polymorphism 👉 Achieved using Method Overriding class Animal { void sound() { System.out.println("Some sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks!"); } } Animal a = new Dog(); a.sound(); // Dog barks! ✔ Parent reference → child object ✔ Decided at runtime 💡 Real-time Example 🎮 Game Character Same action → "attack()" Warrior → uses sword ⚔️ Archer → uses bow 🏹 Mage → casts spell 🔮 👉 Same method → different behaviour ⚠️ Interview Trap 👉 Can we achieve polymorphism without inheritance? ✔ YES (Using Method Overloading) ❌ NO (for Runtime polymorphism – needs inheritance) 💡 Quick Summary TypeMethodTimeExampleCompile-TimeOverloadingCompile Timeadd()RuntimeOverridingRuntimesound() 🔹 Why Polymorphism matters? ✔ Cleaner code ✔ Easy to extend ✔ Reduces duplication ✔ Helps in real-world system design 🔹 Next Topic → Encapsulation in Java 🔐 Which type do you find tricky — Compile-time or Runtime? Drop 👇 #Java #JavaProgramming #Polymorphism #OOPs #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
🚀 LeetCode Practice – Longest Common Prefix (Java) Continuing my DSA practice series, today I solved the Longest Common Prefix problem. 📌 Problem Statement Write a function to find the longest common prefix among an array of strings. If there is no common prefix, return an empty string "". Example: Input - ["flower","flow","flight"] Output - "fl" 💡 Optimized Approach (Sorting Trick) Key Idea: If we sort the array of strings, the strings with the most differences will move to the first and last positions. So the longest common prefix of the entire array must be the common prefix between the first and last string. Example: Original: ["flower","flow","flight"] After sorting: ["flight","flow","flower"] Now we only compare: first = "flight" last = "flower" Common prefix: f ✔ l ✔ i ✖ Result:- "fl" 💻 Java Code import java.util.Arrays; class Solution { public String longestCommonPrefix(String[] strs) { StringBuilder s = new StringBuilder(); Arrays.sort(strs); char first[] = strs[0].toCharArray(); char last[] = strs[strs.length - 1].toCharArray(); for(int i = 0; i < first.length; i++){ if(first[i] != last[i]){ break; } else { s.append(first[i]); } } return s.toString(); } } ⚡ Time Complexity - O(n log n) Because we sort the array. ⚡ Space Complexity - O(1) 📚 Key Learning Sorting the strings allows us to reduce the comparison to only two strings instead of all strings, which simplifies the logic significantly. Consistent DSA practice helps improve problem-solving ability and coding efficiency for technical interviews. #leetcode #java #datastructures #algorithms #codingpractice #softwaredevelopment
To view or add a comment, sign in
-
𝐂𝐚𝐧 𝐰𝐞 𝐨𝐯𝐞𝐫𝐫𝐢𝐝𝐞 𝐭𝐡𝐞 "𝐦𝐚𝐢𝐧()" 𝐦𝐞𝐭𝐡𝐨𝐝 𝐢𝐧 𝐉𝐚𝐯𝐚? In my previous post, we discussed that the "main()" method is static. No — we cannot override the "main()" method Why ? Because "main()" is static. And we cannot override static methods And in Java: 📃Overriding happens at runtime ⏱️ 📃 It depends on objects 👤 But ❌ Static methods belong to the class ❌ They are loaded during class loading time (before objects are created) 🔍𝐖𝐡𝐚𝐭 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐡𝐚𝐩𝐩𝐞𝐧𝐬 𝐭𝐡𝐞𝐧? You can write a main() method in a child class ❌ But it does not override the parent’s main(). It’s called "𝐌𝐞𝐭𝐡𝐨𝐝 𝐇𝐢𝐝𝐢𝐧𝐠". 𝐜𝐥𝐚𝐬𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐏𝐚𝐫𝐞𝐧𝐭 𝐦𝐚𝐢𝐧"); } } 𝐜𝐥𝐚𝐬𝐬 𝐂𝐡𝐢𝐥𝐝 𝐞𝐱𝐭𝐞𝐧𝐝𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐂𝐡𝐢𝐥𝐝 𝐦𝐚𝐢𝐧"); } } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐏𝐚𝐫𝐞𝐧𝐭 𝐩 = 𝐧𝐞𝐰 𝐂𝐡𝐢𝐥𝐝(); 𝐩.𝐦𝐚𝐢𝐧(𝐚𝐫𝐠𝐬); // 𝐜𝐚𝐥𝐥𝐬 𝐏𝐚𝐫𝐞𝐧𝐭 𝐦𝐚𝐢𝐧 𝐂𝐡𝐢𝐥𝐝.𝐦𝐚𝐢𝐧(𝐚𝐫𝐠𝐬); // 𝐜𝐚𝐥𝐥𝐬 𝐂𝐡𝐢𝐥𝐝 𝐦𝐚𝐢𝐧 } } Output : Parent main Child main ♟️These main() methods are not called automatically by the JVM — they run only when we explicitly invoke them. ♟️Only main(String[] args) is invoked automatically by JVM. Other overloaded or hidden main() methods are executed only when explicitly called. 🚀 𝐅𝐢𝐧𝐚𝐥 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 "main()" method cannot be overridden because it is static — it can only be hidden #Java #JavaDeveloper #JavaBackend #Programming #TechJourney #LearnBySharing #JavaConcepts #OOP #InterviewPrep
To view or add a comment, sign in
-
🚀 Day 93 of My 100 Days LeetCode Challenge | Java Today’s problem explored recursion and backtracking, focusing on generating valid strings under specific constraints. The challenge was to generate happy strings of length n, where: The string consists only of 'a', 'b', and 'c' No two adjacent characters are the same From all possible happy strings, the goal was to find the k-th lexicographical string. To solve this, I used a backtracking approach that builds the string step by step. At each step, we try adding characters while ensuring they don't match the previous character. This naturally generates all valid happy strings in lexicographical order. Once all valid strings are generated, we simply return the k-th one if it exists. ✅ Problem Solved: The k-th Lexicographical Happy String of Length n ✔️ All test cases passed (345/345) ⏱️ Runtime: 22 ms 🧠 Approach: Backtracking + Recursion 🧩 Key Learnings: ● Backtracking is ideal for generating constrained combinations. ● Pruning invalid states early improves efficiency. ● Recursion makes exploring possible paths intuitive. ● Lexicographical generation often comes naturally with ordered iteration. ● Constraint-based string generation is a common interview pattern. This problem was a great exercise in systematically exploring possibilities while enforcing constraints. 🔥 Day 93 complete — strengthening recursion and backtracking intuition. #LeetCode #100DaysOfCode #Java #Backtracking #Recursion #ProblemSolving #DSA #CodingJourney #Consistency
To view or add a comment, sign in
-
-
Before Java… Writing software wasn’t “coding”. It was survival. ... You wrote a program on one machine. Tried running it somewhere else? It broke. Different OS. Different CPU. Different behavior. Same code. Completely different results. ... So what did developers do? Rewrite everything. Again. And again. And again. ... This wasn’t engineering. This was chaos. Then Java showed up. And quietly changed everything. ... Instead of running directly on the system… Java introduced something new: 👉 A middle layer. The Java Virtual Machine (JVM) --- Now the process looked like this: Write code once → Compile to bytecode → Run anywhere with JVM --- No more rewriting. No more platform headaches. No more “it works on my machine”. --- This idea sounds obvious today. But back then? It was revolutionary. --- Java didn’t just make things easier. It made software scalable. And almost every modern system today… Still follows this philosophy. --- If Java never existed… What do you think would have replaced it? Or would we still be rewriting code for every machine? Curious to hear your take 👇 #Java #Programming #ComputerScience #SoftwareEngineering #Developers #Coding #PolarisSchoolOfTechnology #MedhaviSkillsUniveristy
To view or add a comment, sign in
-
-
🚀 Deep Dive into Java String Algorithms: From Basics to Palindromes I recently wrapped up an intensive session focused on mastering String manipulation in Java, specifically focusing on substrings and algorithmic problem-solving. It was a powerful reminder that complex problems become simple when you break them down into smaller, manageable parts. Here are the key takeaways from the session: 🔹 Subarrays vs. Substrings: One of the most important realizations was that the logic for printing all subarrays and substrings is essentially the same. The transition from handling primitive arrays to String objects is seamless once you understand how to manage indices using loops and s.charAt(). 🔹 Algorithmic Efficiency: We explored how to find the Longest Palindromic Substring by: Breaking down the problem: First, ensure you can print every possible substring. Optimizing the search: Reversing the size loop allows you to find the longest potential candidate first. Two-Pointer Palindrome Check: Implementing a check using two indexing variables (i and j) to compare characters from both ends without the overhead of reversing the string. 🔹 Debugging & Exceptions: We had a fascinating discussion on StringIndexOutOfBoundsException. A key insight was how the way you write your code—such as storing a value in a variable versus printing it directly—can determine exactly when and how an exception is triggered during execution. 🔹 Practical Application: Beyond theory, we implemented logic to: Find if one string is a contiguous substring of another. Count occurrences of a specific substring within a larger text. Handle case sensitivity using equalsIgnoreCase() for more robust comparisons. The Road Ahead: The session concluded with a "six-output" challenge—a complex assignment requiring us to reverse individual words in a sentence, count character lengths, and manipulate sentence structures (e.g., "India is my country"). As we move into a short break, the goal is clear: consistency. Whether it's five hours of deep practice or solving just two problems on the worst of days, staying in touch with the code is what builds mastery. #Java #Coding #SoftwareDevelopment #Algorithms #DataStructures #LearningJourney TAP Academy
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