0

How static affects methods in polymorphism?

class Parent { public static void show() { System.out.println("parent class"); } } class Child extends Parent { public static void show() { System.out.println("child class"); } } public class Program{ public static void main(String[] args) { Parent p = new Child(); p.show(); } } Even when p object has the reference of the child class, when p is used to call the show it prints "parent class" why? Is it the show method in parent class is declared global so methods in child class can not overridden? If so then how to access the same method in child class?

9th Jun 2019, 3:50 AM
Heisenberg
Heisenberg - avatar
1 Resposta
+ 1
Static methods are "statically bound" and normal methods are "dynamically bound" which exactly leads to the behaviour you are describing. That distinction will make more sense if you are programming C++ where you control that yourself explicitly! To access `Child`s method, you will need to downcast the object again: Parent p = new Child(); ((Child)p).show(); But of course, the cool thing about static methods is that they don't belong to any object. So I really prefer a simple: Child.show();
9th Jun 2019, 4:04 AM
Schindlabua
Schindlabua - avatar