Java Runtime Polymorphism and Inheritance Concepts

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

To view or add a comment, sign in

Explore content categories