In: Computer Science
Consider a class ‘A’ with a method public static void show( ). A
class ‘Derived’ is the subclass of ‘A’.
Is it possible to define the same method public static void show( )
in the Derived class. Why give reasons? Is it run time
polymorphism? (0.5 Marks)
Is it possible to define the method public void show( ) (non static
method) in the Derived class. What will happen and why give
reasons?
Answer-
Yes, it's possible we can declare the same static method in the derived class but its identity is different from the static method in the base class. It's called method hiding means derived class hides the implementation of the base class static members although the static members are accessible. Inn simple language we can say base class static methods are not the part of a derived class method. Both of them have a different identity as the static method belongs to the class, not to the object so the calling is decided by the compiler itself.
Runtime polymorphism means that the binding would be done at the run time. But in the given scenario,the compiler will decide at the compile time to execute which method since static methods can't be overridden and static methods uses the static binding means bonded by the compiler. So the binding is done in the compile-time only. Thus this scenario can't be run-time polymorphism.
No, its not possible to declare same non static method in the derived class because we are changing the return type of the method from static to non static that leads to method overridden or polymorphism which can't be performed by the static methods.If we declare same static method then the base class method can be hidden but here the scenario is different and static members are not polymorphic which leads to no overriding.
So,while executing this scenario,it will show an error that method can't be overriden.