Home > Java > Method Overriding in Java: – PART-1

Method Overriding in Java: – PART-1

What is method overriding?

  • If a subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
  • In other words, if a subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.
  • Declaring a method in subclass which is already present in parent class is known as method overriding.
  • In object-oriented terms, overriding means to override the functionality of an existing method.
  • Method overriding is the example of run time polymorphism (Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic).
  • When a method in a sub class has same name and type signature as a method in its super class, then the method is known as overridden method.
  • The key benefit of overriding is the ability to define method that’s specific to a particular subclass type.
  • Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
  • Method overriding occurs in two classes that have IS-A (inheritance) relationship.

 

Understanding the problem without method overriding

Let’s understand the problem that we may face in the program if we don’t use method overriding.

 

So to provide a specific implementation of run() method in subclass we use method overriding.

 

Method overriding examples

Example 1

Here we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so method overriding happens here.

 

 

 

Example 2:-

 

 

Example 3:-

 

…continued in the next article Method Overriding in Java: – PART-2

This Article is TAGGED in , , . BOOKMARK THE permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">