I observe a behavior that when we call a variable from a polymorphic object, then it calls the parent variable, but when we call the method with the same polymorphic object, then it calls the child method. Why is this polymorphism behavior in Java? Why doesn't Java handle polymorphic variables and methods in the same way?
class Parent{ int age =10; public void showAge(){ System.out.println("Parent Age:"+age); } } class ChildOne extends Parent{ int age = 20; public void showAge(){ System.out.println("child one age:"+age); } } class ChildTwo extends Parent{ int age = 30; public void showAge(){ System.out.println("Child Two Age:"+age); } } public class Test{ public static void main(String[] args) { Parent parentChildOne = new ChildOne(); System.out.println("parentChildOne.age: "+parentChildOne.age); parentChildOne.showAge(); Parent parentChildTwo = new ChildTwo(); System.out.println("parentChildTwo.age: "+parentChildTwo.age); parentChildTwo.showAge(); } }
Here is the result:
parentChildOne.age: 10 child one age:20 parentChildTwo.age: 10 Child Two Age:30
source share