Runtime polymorphism
Method overriding is one of the way by which java achieve 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.
Rules for overriding method
Access-Modifiers : 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 super-class can be made public, but not private, in the subclass. Doing so, will generate compile-time error.
class Parent {
private void m1()
{
System.out.println("From parent m1()");
}
protected void m2()
{
System.out.println("From parent m2()");
}
}
class Child extends Parent {
private void m1() {
System.out.println("From child m1( )");
}
public void m2( )
{
System.out.println("From child m2()");
}
}
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.m2();
Parent obj2 = new Child();
obj2.m2();
}
}
Output : -
From parent m2()
From child m2()
Final methods can not be overridden : If we don’t want a method to be overridden, we declare it as final.
class Parent {
// Can't be overridden
final void show() { }
}
class Child extends Parent {
// This would produce error
void show() { }
}
Static methods can not be overridden : When you define a static method with same signature as a static method in base class, it is known as method hiding.
Private methods can not be overridden : Private methods cannot be overridden as they are bonded during compile time. Therefore we can’t even override private methods in a subclass.
Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword.
Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).
Overriding and abstract method: Abstract methods in an interface or abstract class are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown.
Негізгі бет Java 26 | Runtime polymorphism | Rules for Method Overriding
Пікірлер: 1