Previous | Home | Next |
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. Child class has the same method as of base class. In such cases child class overrides the parent class method without even touching the source code of the base class. This feature is known as method overriding.
Upcasting
When Parent class reference variable refers to Child class object, it is known as Upcasting.
Example :
class A{} class B extends A{} A a=new B();//upcasting
Rules for Method Overriding
- applies only to inherited methods.
- object type (NOT reference variable type) determines which overridden method will be used at runtime.
- Overriding method must not have more restrictive access modifier.
- Abstract methods must be overridden.
- Static and final methods cannot be overridden.
- Constructors cannot be overridden.
- It is also known as Runtime polymorphism.
Example :
class X { public void methodA() //Base class method { System.out.println ("hello, methodA of class X"); } } class Y extends X { public void methodA() //Derived Class method { System.out.println ("hello, methodA of class Y"); } } class Z { public static void main (String args []) { X obj1 = new X(); // Reference and object X X obj2 = new Y(); // X reference but Y object obj1.methodA(); obj2.methodA(); } }
Output :
hello, I' methodA of class X hello, I' methodA of class Y
Previous | Home | Next |