A feature known as overriding in any object-oriented programming
language enables a subclass or child class to offer a particular
implementation of a method that is already given by one of its
super-classes or parent classes. Whenever a method in a subclass
shares the same name, parameters, signature, and return type (or
sub-type) as a method in its superclass, the subclass method is said
to override the superclass method.
Method overriding is one approach for Java to implement Run Time Polymorphism. The
object that is used to initiate a method determines the version of the method that
is executed.
When a method is called by an object of a parent class, the parent class's method
definition is executed.
But when a method is called from an object of a subclass, the version of the child
class's (subclass') method defined is executed. In other words, which version of an
overridden
method gets performed is determined by the type of the object being referenced to
(not the type of the reference variable).
Java refers to this as method
overriding when
a subclass (child class) has a method that is identical to one that is declared in
the parent class.
In simple terms, method overriding refers to the process of
defining own unique implementation of a method by subclass that was originally
defined by its parent class.
// Java method overridden example
class Animal { void Move(){ System.out.println("Animals is Moving"); } void Eat(){ System.out.println("Animals is Eating"); } } class Dog extends Animal { @Override void Move(){ // here overriding take place System.out.println("Dog is Moving"); } @Override void Eat(){ System.out.println("Dog is Eating"); } } class DockerTpoint { public static void main(String[] args) { Animal animal = new Animal(); // If a Animal type reference refers to a Animal object, then Animal animal.Move(); // move or eat is called animal.Eat(); Animal animal2 = new Dog(); // If a Animal type reference refers animal2.Move();// to a Dog (Child) object Dog's eat() & Move(), animal2.Eat(); // then it is called. This is called RUN TIME POLYMORPHISM. } }
Output:
Animals is Moving
Animals is Eating
Dog is Moving
Dog is Eating
// Java program with method Overriding
class Employee { public static int Salary = 15000; void salary(){ System.out.println("Salary : "+Salary); } } class Manager extends Employee { // salary metod get override bt salary() of Employee Class void salary(){ System.out.println("Manager Salary : "+(Salary+10000)); } } class Clerk extends Employee { void salary(){ // salary metod get override bt salary() of Employee Class System.out.println("Clerk Salary : "+(Salary+20000)); } } class DockerTpoint { public static void main(String[] args){ Employee employee = new Manager(); employee.salary(); Employee employee2 = new Clerk(); employee2.salary(); } }
Output:
Manager Salary : 25000
Clerk Salary : 35000
Post your comment