Page 363 - CITS - Computer Software Application -TT
P. 363
COMPUTER SOFTWARE APPLICATION - CITS
Method overriding is one of the ways by which Java achieves Run Time Polymorphism. The version of a method
that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to
invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to
invoke the method, then the version in the child class will be executed. In other words, it is the type of the object
being referred to (not the type of the reference variable) that determines which version of an overridden method
will be executed.
Example of Method Overriding in Java
Java program to demonstrate method overriding in java
// Base Class
class Parent {
void show() { System.out.println(“Parent’s show()”); }
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
Override void show()
{
System.out.println(“Child’s show()”);
}
}
// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent’s
// show is called
Parent obj1 = new Parent();
obj1.show();
// If a Parent type reference refers to a Child object Child’s show() is called. This is called RUN TIME
POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}
1 Rules for Java Method Overriding
The access modifier for an overriding method can allow more, but not less, access than the overridden method.
For example, a protected instance method in the superclass can be made public, but not private, in the subclass.
Doing so will generate a compile-time error.
A Simple Java program to demonstrate Overriding and Access-Modifiers
class Parent {
// private methods are not overridden
350
CITS : IT&ITES - Computer Software Application - Lesson 94 - 100