Day 43-Understanding Runtime Polymorphism in Java If compile-time polymorphism is about decisions made early, runtime polymorphism is where things get interesting — decisions are made while the program is running. What is Runtime Polymorphism? Runtime polymorphism is the ability of a program to decide which method to execute at runtime based on the object. It is achieved using method overriding. 🔹 Simple Idea: Same method name, same parameters… but different behavior depending on the object. 🔹 Example: class Card { void swipe() { System.out.println("Please wait..."); } } class CreditCard extends Card { void swipe() { System.out.println("Payment via Credit Card"); } } class DebitCard extends Card { void swipe() { System.out.println("Payment via Debit Card"); } } public class Main { public static void main(String[] args) { Card c; c = new CreditCard(); c.swipe(); // Credit Card method c = new DebitCard(); c.swipe(); // Debit Card method } } 🔹 What’s happening here? - The reference type is Card - But the object changes (CreditCard / DebitCard) - JVM decides which method to call at runtime 🔹 Key Points: ✔ Happens at runtime (execution time) ✔ Achieved using method overriding ✔ Also called Dynamic Binding / Late Binding ✔ JVM decides method execution based on actual object This is what makes Java powerful and flexible in real-world applications. #Java #OOP #Polymorphism #CodingJourney #ProgrammingBasics
Java Runtime Polymorphism Explained
More Relevant Posts
-
𝗘𝘃𝗲𝗿 𝗵𝗲𝗮𝗿𝗱 𝗼𝗳 𝗮 𝘁𝗵𝗿𝗲𝗮𝗱 𝘄𝗮𝗸𝗲 𝘂𝗽...𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗯𝗲𝗶𝗻𝗴 𝗻𝗼𝘁𝗶𝗳𝗶𝗲𝗱? No notify(), no interrupt() and yet it continues execution. That’s where I learnt about the 𝗦𝗽𝘂𝗿𝗶𝗼𝘂𝘀 𝗪𝗮𝗸𝗲𝘂𝗽 in Java threads. 𝗔 𝗦𝗽𝘂𝗿𝗶𝗼𝘂𝘀 𝗪𝗮𝗸𝗲𝘂𝗽 in Java threads occurs when a thread in the waiting state wakes up without being notified or without any explicit thread method. 𝗪𝗵𝘆 𝗱𝗼𝗲𝘀 𝗶𝘁 𝗵𝗮𝗽𝗽𝗲𝗻? - The JVM does not control thread execution entirely; execution relies on the operating system. OS thread systems (like pthreads) wake up threads randomly. - It is by design; Java explicitly allows this behaviour. - Java and OS don't guarantee threads wake up when notified, as it can impact the overall performance. 𝗪𝗵𝗮𝘁 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝗶𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝗹𝘆? 1. lock.wait() is called 2. The thread releases the monitor lock and goes to the waiting state. 3. JVM/OS maintains a wait queue for the object. 4. Ideally, threads wakes when notify()/notifyAll() methods is called. BUT JVM/OS can remove the thread from the wait queue randomly and put it into the runnable state. How to prevent issues due to spurious wakeups? Never use "if" with "wait()" method, always use "while" public synchronized void consume() throws InterruptedException { if (queue.isEmpty()) { wait(); // may wake up spuriously } int item = queue.remove(); } In case of a spurious wakeup, queue.remove() will execute directly. If the queue is empty, it will throw an exception. public synchronized void consume() throws InterruptedException { while (queue.isEmpty()) { wait(); // may wake up spuriously } int item = queue.remove(); } In this case, even if a spurious wakeup happens, the while loop rechecks the condition. If the queue is still empty, it goes back to the waiting state again, preventing any exceptions/errors. Have you ever faced a spurious wakeup in production or in your personal projects? Let's discuss in comments.
To view or add a comment, sign in
-
Java- Automatic Type Promotion of Primitives I am trying to explore and explain the concept of automatic type promotion of primitives using a simple code in java using two byte values: class TestAutomatictypepromotion{ public static void main(String[] ar){ byte a=10; byte b=20; int sum=a+b; System.out.println(sum); }} Perfect! Let me prove the byte → int promotion step by step through actual bytecode analysis.We have the real bytecode. Now let me build the full visual explanation. javac your souce code javap -c TestAutomatictypepromotion.class (we will get the vyte code) The 3 smoking-gun proofs from the actual bytecode Here is the raw javap -c output from your exact code, with the proof highlighted: 0: bipush 10 ← pushes 10 as INT (not byte) 2: istore_1 ← "i" = integer store (no bstore exists!) 3: bipush 20 ← pushes 20 as INT 5: istore_2 ← integer store 6: iload_1 ← "i" = integer load (no bload exists!) 7: iload_2 ← integer load 8: iadd ← "i" = INTEGER add ← THE KEY PROOF 9: istore_3 Proof 1 — iload, not bload: When a and b are loaded from local variable slots, the opcode is iload_1 and iload_2. The i prefix means integer. There is literally no bload instruction in the entire JVM specification. Proof 2 — iadd, not badd: The addition uses iadd. There is no badd opcode. The JVM arithmetic instruction set only has iadd, ladd, fadd, dadd (int, long, float, double). Bytes have no dedicated add — they must become ints first. Proof 3 — println:(I)V: The method descriptor in constant pool entry #13 is println:(I)V. The I is the JVM type descriptor for int. So even println receives an int, not a byte. Why does Java do this? The JVM's operand stack and local variable slots work natively in 32-bit units. Byte, short, char, and boolean values are all widened to int the moment they enter the stack — this is called numeric promotion. It's defined in the JLS §5.6.1 (Unary Numeric Promotion) and §5.6.2 (Binary Numeric Promotion). The JVM spec simply has no byte-level arithmetic opcodes — they were intentionally omitted to keep the instruction set small and the stack 32-bit aligned. Want me to show what happens when the result overflows a byte, or demonstrate why byte c = a + b causes a compile-time error without an explicit cast: Let me cover both — byte overflow AND the compile-time error proof through actual bytecode! byte data type has a range: -128 to 127 Assume we declare the variables llike : byte b=100.byte b=100; then try to add both (byte values) like byte c=a+b; The result :200 is not in byte range. So overflow happens. Compiler will not allow. The compiled and interpreted way in Java is the base for such standard code. Most developers fear the JVM. Java developers understand it. Codeest Software Factory Anirudh Mangore Sandip Magdum Mehvish Fansopkar Mitali Dere Sakshi Randive Shruti Chavan NILESH GHAVATE Shaikh Abdulkhadir Java Recruiting Group,OpenJDK
To view or add a comment, sign in
-
Small concept. Big impact. In Java: byte + byte = int That’s automatic type promotion — and it’s one of those things that silently causes bugs if you don’t fully understand it. Back to basics = better code.
Java- Automatic Type Promotion of Primitives I am trying to explore and explain the concept of automatic type promotion of primitives using a simple code in java using two byte values: class TestAutomatictypepromotion{ public static void main(String[] ar){ byte a=10; byte b=20; int sum=a+b; System.out.println(sum); }} Perfect! Let me prove the byte → int promotion step by step through actual bytecode analysis.We have the real bytecode. Now let me build the full visual explanation. javac your souce code javap -c TestAutomatictypepromotion.class (we will get the vyte code) The 3 smoking-gun proofs from the actual bytecode Here is the raw javap -c output from your exact code, with the proof highlighted: 0: bipush 10 ← pushes 10 as INT (not byte) 2: istore_1 ← "i" = integer store (no bstore exists!) 3: bipush 20 ← pushes 20 as INT 5: istore_2 ← integer store 6: iload_1 ← "i" = integer load (no bload exists!) 7: iload_2 ← integer load 8: iadd ← "i" = INTEGER add ← THE KEY PROOF 9: istore_3 Proof 1 — iload, not bload: When a and b are loaded from local variable slots, the opcode is iload_1 and iload_2. The i prefix means integer. There is literally no bload instruction in the entire JVM specification. Proof 2 — iadd, not badd: The addition uses iadd. There is no badd opcode. The JVM arithmetic instruction set only has iadd, ladd, fadd, dadd (int, long, float, double). Bytes have no dedicated add — they must become ints first. Proof 3 — println:(I)V: The method descriptor in constant pool entry #13 is println:(I)V. The I is the JVM type descriptor for int. So even println receives an int, not a byte. Why does Java do this? The JVM's operand stack and local variable slots work natively in 32-bit units. Byte, short, char, and boolean values are all widened to int the moment they enter the stack — this is called numeric promotion. It's defined in the JLS §5.6.1 (Unary Numeric Promotion) and §5.6.2 (Binary Numeric Promotion). The JVM spec simply has no byte-level arithmetic opcodes — they were intentionally omitted to keep the instruction set small and the stack 32-bit aligned. Want me to show what happens when the result overflows a byte, or demonstrate why byte c = a + b causes a compile-time error without an explicit cast: Let me cover both — byte overflow AND the compile-time error proof through actual bytecode! byte data type has a range: -128 to 127 Assume we declare the variables llike : byte b=100.byte b=100; then try to add both (byte values) like byte c=a+b; The result :200 is not in byte range. So overflow happens. Compiler will not allow. The compiled and interpreted way in Java is the base for such standard code. Most developers fear the JVM. Java developers understand it. Codeest Software Factory Anirudh Mangore Sandip Magdum Mehvish Fansopkar Mitali Dere Sakshi Randive Shruti Chavan NILESH GHAVATE Shaikh Abdulkhadir Java Recruiting Group,OpenJDK
To view or add a comment, sign in
-
Master method overriding and polymorphism in Java through clear examples like Animal and Payment systems. Learn to write flexible, clean code
To view or add a comment, sign in
-
Leetcode Practice - 8. String to Integer (atoi) The problem is solved using JAVA. Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: ✔ Whitespace: Ignore any leading whitespace (" "). ✔ Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. ✔ Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. ✔ Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
🚀 Day 5 of my Java journey — Abstraction, Enums, Lambda! Today was a deep dive into some of the most powerful features of Java! 🔥 🏗️ Abstract Class — deeper understanding ✅ Abstract class cannot be instantiated directly ✅ BUT you can create an anonymous class from it on the spot! ✅ This is how Java gives flexibility without creating a full new class 🔗 Interface — deeper concepts ✅ Interface can extend another interface ✅ A class can implement multiple interfaces ✅ Deep abstraction — hide implementation, show only what matters 🎯 Types of Interfaces in Java ✅ Normal interface — only abstract methods ✅ Functional interface — exactly ONE abstract method (used with lambda!) ✅ Marker interface — no methods at all, just marks a class (e.g. Serializable) 🔢 Enum in Java ✅ Enum = a fixed set of constants ✅ Example: Days of week, Directions (NORTH, SOUTH, EAST, WEST) ✅ Much safer than using plain int or String constants 💡 Functional Interface + Lambda Expression ✅ @FunctionalInterface annotation — only 1 abstract method allowed ✅ Lambda replaces the need to write a full class! ✅ Before lambda: create a class, implement method, create object ✅ With lambda: just write the logic in one line — clean and powerful! Example: A obj = (int a) -> { System.out.println("Hello from lambda!"); }; obj.show(5); Java is getting more and more interesting every day! 🚀 Day 1 ✅ | Day 2 ✅ | Day 3 ✅ | Day 4 ✅ | Day 5 ✅ ... #Java #JavaDeveloper #Lambda #FunctionalInterface #Enum #Abstraction #100DaysOfCode #BackendDevelopment #TechCareer #LearningToCode
To view or add a comment, sign in
-
💻 Generics in Java — Write Flexible & Type-Safe Code 🚀 If you’ve ever faced ClassCastException or messy type casting… Generics are your solution 🔥 This visual breaks down Java Generics in a simple yet practical way 👇 🧠 What are Generics? Generics allow you to write type-safe and reusable code by using type parameters (<T>). 👉 Instead of hardcoding data types, you write code that works with any type 🔍 Why Generics? ✔ Eliminates explicit type casting ✔ Ensures compile-time type safety ✔ Improves code reusability ✔ Makes code cleaner and readable 🔄 Core Concepts: 🔹 Generic Class class Box<T> { T data; } 👉 Same class → works with String, Integer, etc. 🔹 Generic Method public <T> void printArray(T[] arr) 👉 Works for any data type 🔹 Bounded Types <T extends Number> 👉 Restrict types (only numbers allowed) 🔹 Wildcards (?) <?> → Any type <? extends T> → Upper bound <? super T> → Lower bound 🔹 Type Inference (Diamond Operator) List<String> list = new ArrayList<>(); 👉 Cleaner code, compiler infers type ⚡ Generics with Collections: List<String> names = new ArrayList<>(); 👉 Ensures only String values are stored 💡 Real impact: Without generics → Runtime errors ❌ With generics → Compile-time safety ✅ 🎯 Key takeaway: Generics are not just syntax — they are the foundation of writing robust, scalable, and reusable Java code. #Java #Generics #Programming #BackendDevelopment #SoftwareEngineering #Coding #100DaysOfCode #Learning
To view or add a comment, sign in
-
-
💻 Generics in Java — Write Flexible & Type-Safe Code 🚀 If you’ve ever faced ClassCastException or messy type casting… Generics are your solution 🔥 This visual breaks down Java Generics in a simple yet practical way 👇 🧠 What are Generics? Generics allow you to write type-safe and reusable code by using type parameters (<T>). 👉 Instead of hardcoding data types, you write code that works with any type 🔍 Why Generics? ✔ Eliminates explicit type casting ✔ Ensures compile-time type safety ✔ Improves code reusability ✔ Makes code cleaner and readable 🔄 Core Concepts: 🔹 Generic Class class Box<T> { T data; } 👉 Same class → works with String, Integer, etc. 🔹 Generic Method public <T> void printArray(T[] arr) 👉 Works for any data type 🔹 Bounded Types <T extends Number> 👉 Restrict types (only numbers allowed) 🔹 Wildcards (?) <?> → Any type <? extends T> → Upper bound <? super T> → Lower bound 🔹 Type Inference (Diamond Operator) List<String> list = new ArrayList<>(); 👉 Cleaner code, compiler infers type ⚡ Generics with Collections: List<String> names = new ArrayList<>(); 👉 Ensures only String values are stored 💡 Real impact: Without generics → Runtime errors ❌ With generics → Compile-time safety ✅ 🎯 Key takeaway: Generics are not just syntax — they are the foundation of writing robust, scalable, and reusable Java code. #Java #Generics #Programming #BackendDevelopment #SoftwareEngineering #Coding #100DaysOfCode #Learning
To view or add a comment, sign in
-
-
🚀 Day -2 JDK, JRE, JVM Journey with Frontlines EduTech (FLM) and Fayaz S JDK:- 👉 JDK means Java Development kit 👉 Which is collection of the following components 1. Java compiler 2. JVM, 3. Java library ** Simple:- JDK = JRE+ Development kit JRE:- JRE means Java Runtime Environment Which is collection of Java library and JVM JRE is an internal partition of JDK **Simple:- JRE = JVM+library needed to run program JVM:- JVM means Java virtual machine It runs Java Byte code It converts Byte code into machine code and makes Java platform Independent. ** Simple:- JVM ----> Engine that runs Java program. JVM has 3 components 1. CLSS 2. Memory management 3. Execution engine 1.CLSS ----> class loader subsystem load all .class files Verifies all .class filed Links Initialises 2. Memory management:- 👉 Method area ---> static variable, static methods ----> Class meta data link Name, package, parent classes 👉 Heap Area:- ---> Instance Variable ----> objects references 👉 Static area:- Collapse time to time It is stores local variables Threads information is have 👉 Program Counters:- Pointing Current instructions Update next instruction 👉 Native stack area:- Related to other languages (C, C++) 3. Execution engine:- 👉 Interprtor Execute the .class file 👉 JIT compiler Just in time compiler Finds the repetitive code Executes in a single shot Hybrid Language 👉 Garbage collector Collection all unused references/ memoryfreeUp. #corejava #JDK #JRE #JVM #FrontlinesEduTech
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