Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
community creator

How to do method overriding in Java

Smriti Mallick

Method overriding occurs when a method in the subclass has the same name and signature as a method in its superclass.

In such cases, the version of the called overridden method will always refer to the method defined by the subclass.

Why overridden methods?

Polymorphism is essential in object-oriented programming for one reason: it allows a general class to specify methods that will be common to all its derivatives while also allowing subclasses to define the specific implementations of some or all of those methods.

Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of polymorphism.

widget

Implementing method overriding

Here is an example illustrating method overriding in Java:

class Apple
 {
   void show() 
   {
      System.out.println("I am an apple.");
   }
}

class Cherry extends Apple
{
   void show() 
   {
      System.out.println("I am a cherry.");
   }
}

class Fruits {
   public static void main(String[] args)
   {
      Cherry c1 = new Cherry();
      c1.show();
   }
}

In the example above, we have two methods that have the same and signature (i.e., show()), but are in two different classes. Here, the Cherry class extends Apple; thus, becoming the sub-class.

When the show() method is called in the main class (i.e., Fruits), it directly refers to the version in sub-class by avoiding the super class’s show() method and printing the message in the show() method in class Cherry.

Thanks for reading.
Happy Coding :)

RELATED TAGS

java
community creator
RELATED COURSES

View all Courses

Keep Exploring