Overriding method is different than overloading, as in overloading of a method, their are more than one method with same name but different parameter with in same class unlike this, In overriding of a method, a method in child class(sub class) has the same name as of its parent class(super class).
Rules of overriding a method
- The method names must be same in
this process.
- We can only overridden a instance
method if child class inherit them.
- A method which is declared final by
using final keyword can not be
overridden.
- A child class which is in a
different package can only override
a non-final method which are
declared either public or protected.
- we cannot overridden constructors.
- If we are unable to inherit a
method, then we cannot overridden
it.
Syntax
class className1
{
// methods
rtype1 methodName(parameter1)
{
//statements
}
}
class className2 extends className1
{
// methods
rtype1 methodName(parameter1)
{
// statements
}
}
eg:-
class Vehicle
{
public void move()
{
System.out.println("Vehicle can move");
}
}
class Bike extends Vehicle
{
public void move()
{
System.out.println("Bike can move fast ");
}
}
class MethodOverridingDemo
{
public static void main(String args[])
{
Vehicle vehObj1 = new Vehicle();
Bike bkObj = new Bike();
Vehicle vehObj2 = new Bike();
vehObj1.move();
bkObj.move();
vehObj2.move(); // Dynamic method dispatch
}
}
Output
Vehicle can move
Bike can move fast
Bike can move fast
0 Comment(s)