Java Polymorphism Trick You Didn't Expect! 🤯 | Java Interview Question #shorts #interview #java
Confused why this prints 10 instead of 20 in Java? Let's break it down!
You might expect System.out.println(obj.value) to print 20, since obj is created as a Child. But Java prints 10 — why?
That’s because Java only uses polymorphism for methods, not for variables (fields). Even though obj is an instance of Child, it’s declared as a Parent, so Java accesses the value field from the Parent class.
This is called field hiding, not overriding. Java decides which variable to access based on the reference type — not the actual object type.
It's a common trap in coding interviews and real projects!
👍 Follow @CodeSnap-UR for more Java tips, tricks, and interview-ready explanations!
Видео Java Polymorphism Trick You Didn't Expect! 🤯 | Java Interview Question #shorts #interview #java канала CodeSnap
You might expect System.out.println(obj.value) to print 20, since obj is created as a Child. But Java prints 10 — why?
That’s because Java only uses polymorphism for methods, not for variables (fields). Even though obj is an instance of Child, it’s declared as a Parent, so Java accesses the value field from the Parent class.
This is called field hiding, not overriding. Java decides which variable to access based on the reference type — not the actual object type.
It's a common trap in coding interviews and real projects!
👍 Follow @CodeSnap-UR for more Java tips, tricks, and interview-ready explanations!
Видео Java Polymorphism Trick You Didn't Expect! 🤯 | Java Interview Question #shorts #interview #java канала CodeSnap
Комментарии отсутствуют
Информация о видео
3 июня 2025 г. 23:22:41
00:00:15
Другие видео канала