Method Overriding in Java with Rules and Real-time Examples

Method Overriding in Java is a condition when a subclass has the same method as declared in the parent class. Here, a parent class can be called an overridden method. We have already discussed method overriding in Java. Here, you will get a brief description of Method Overriding in Java with some important rules and examples.

So, hit the scroll button and enter into a new world!

Method overriding in Java with Rules and Examples

What is Method Overriding in Java?

In object-oriented programming, the feature of overriding is used to provide a class, subclass or a child class to use a method that is already used by parent class to have a specific implementation.

Method overriding in Java programming occurs when the method in the subclass has the same return type, or parameters, name or signature as the parent class.

Method overriding is the method by which Java can support runtime polymorphism. Basically, the method to execute is chosen on the basis of the type of object and not on the type of reference variable.

Check out the trending difference between Method Overloading and Overriding in Java

Example –

// Base Class
class Parent
{
  void methodOfParentClass()
  {
    System.out.println("Parent's method()");
  }
}
// Inherited class
class Child extends Parent
{
  // This method overrides methodOfParentClass() of Parent
  @Override
  void methodOfParentClass()
  {
    System.out.println("Child's method()");
  }
}
  // Driver class
  class MethodOverriding {
  public static void main(String[] args)
  {
    // If a Parent type reference refers
    // to a Parent object, then Parent's
    // methodOfParentClass is called
    Parent obj1 = new Parent();
    obj1.methodOfParentClass();
    // If a Parent type reference refers
    // to a Child object Child's methodOfParentClass()
    // is called. This is called RUN TIME
    // POLYMORPHISM.
    Parent obj2 = new Child();
    obj2.methodOfParentClass();
  }
}

Output-

method-overriding

Rules for Method Overriding in Java

1. Overriding Access-Modifiers

This method allows more access than the overridden method, it is always more.

Follow this link, to know more about Java Access Modifiers.

Example 

class Parent
{
  //private methods are not overridden
  private void method1()
  {
    System.out.println("From parent method1()");
  }
  protected void method2()
  {
    System.out.println("From parent method2()");
  }
}
class Child extends Parent
{
  //new method1() method
  //unique to Child class
  private void method1()
  {
    System.out.println("From child method1()");
  }
  //overriding method
  //with more accessibility
  @Override
  public void method2()
  {
    System.out.println("From child method2()");
  } 
}
//Driver class
class MethodOverriding
{
  public static void main(String[] args)
  {
    Parent obj1 = new Parent();
    obj1.method2();
    Parent obj2 = new Child();
    obj2.method2();
  }
}

Output-Overriding-and-Java-Access-Modifiers

2. Final Methods cannot be Overridden

When we don’t want the method to be overridden, we declare it as final.

Example-

class Parent
     {
// Can't be overridden
        final void show() {  }
     }
class Child extends Parent
           {
// This would produce error
                void show() {  }
            }

3. Static Methods cannot be Overridden

Method hiding is a process in which a static method has the same signature as the signature of the base class.

Don’t forget to check Static Methods in Java

Static Methods cannot be Overridden

Example-

class Parent
{
  static void method1()
  {
    System.out.println("From parent static method1()");
  }
  void method2()
  {
    System.out.println("From parent non-static(instance) method2()");
  }
}
class Child extends Parent
{
  //This method hides method1() in Parent
  static void method1()
  {
    System.out.println("From child static method1()");
  }
  //This method overrides method2() in Parent
  @Override
  public void method2()
  {
    System.out.println("From child non-static(instance) method2()");
  }
}
//Driver class
class MethodOverriding
{
  public static void main(String[] args)
  {
    Parent obj1 = new Child();
    obj1.method1();
    obj1.method2();
  }
}

Output-Static-Methods-cannot-be-Overridden

4. Overriding Method must have the same return type or subtype

Java 5.0 made it possible to have a different return type in the child class for an overridden method provided that the return type of child class be the same as a subtype of the return type of the parent class. This method is called a covariant return type.

5. Invoking Overridden Method from Sub-Class

To call the parent class method during overriding we use the keyword super.

Example-

//Base Class
class Parent
{
  void methodOfParentClass()
  {
    System.out.println("Parent's Method");
  }
}
//Inherited class
class Child extends Parent
{
  //This method overrides methodOfParentClass of Parent
  @Override
  void methodOfParentClass()
  {
    super.methodOfParentClass();
    System.out.println("Child's Method");
  }
}
//Driver class
class MethodOverriding
{
  public static void main(String[] args)
  {
    Parent obj = new Child();
    obj.methodOfParentClass();
  }
}

Output-must-have-the-same-Return-Type

6. Overriding Java Constructor

Java constructor cannot be the same for a parent class and a subclass because it must always be the same as the class name.

7. Overriding and Exception-Handling in Java

There are two rules that are to be kept in mind while handling exceptions in java.

  • Rule 1 – Throwing a checked expression causes a compile-time error. If the superclass doesn’t throw any exception then the subclass can throw an error.

Example 

class Parent
     {
        void method1()
            {
               System.out.println("From parent method1()");
             }
       void method2()
              {
                System.out.println("From parent  method2()");
              }
       }
class Child extends Parent
{
    @Override
// no issue while throwing unchecked exception
    void method1() throws ArithmeticException
          {
             System.out.println("From child method1()");
           }
    @Override
// compile-time error
// issue while throwin checked exception
    void method2() throws Exception
            {
                 System.out.println("From child method2");
            }
   }

Output-

Compile Time Error

  • Rule 2 – If an exception occurs in a parent class then the compile-time error occurs.

Example 

class Parent
      {
          void method1() throws RuntimeException
              {
                  System.out.println("From parent method1()");
              }
       }
class Child1 extends Parent
         {
              @Override
// no issue while throwing same exception
              void method1() throws RuntimeException
                      {
                           System.out.println("From child1 method1()");
                       }
          }
class Child2 extends Parent
          {
               @Override
// no issue while throwing subclass exception
               void method1() throws ArithmeticException
                      {
                           System.out.println("From child2 method1()");
                      }
           }
class Child3 extends Parent
           {
               @Override
// no issue while not throwing any exception
                void method1()
                    {
                           System.out.println("From child3 method1()");
                    }
           }
class Child4 extends Parent
        {
           @Override
// compile-time error
// issue while throwing parent exception
            void method1() throws Exception
                   {
                       System.out.println("From child4 method1()");
                   }
          }

Output-

Compile Time Error

8. Overriding Abstract Method

Java Abstract methods can only be overridden in concrete classes or else a compile-time error will occur.

9. Overriding Synchronized/Stricfp Method

The presence of a synchronized or stricfp method holds no effect on the overridden method.

Multilevel Method Overriding in Java

//Base Class
class Parent
{
  void show()
  {
    System.out.println("Parent's show()");
  }
}
//Inherited class
class Child extends Parent
{
  //This method overrides show() of Parent
  void show()
  {
    System.out.println("Child's show()");
  }
}
//Inherited class
class GrandChild extends Child
{
  //This method overrides show() of Parent
  void show()
  {
    System.out.println("GrandChild's show()");
  }
}
//Driver class
public class MethodOverriding
{
  public static void main(String args[])
  {
    Parent obj1 = new GrandChild();
    obj1.show();
  }
}

Output-

Multilevel-Method-Overriding-in-Java

Java Quiz

Summary

In conclusion, the class gives its own specific implementation to an inherited method without even modifying the parent class. This article helped us understand the runtime polymorphism better and also help us understand its relation to inheritance in Java.

2 Responses

  1. kiran sahu says:

    Hey,it was a great article.I found it very useful for me please keep posting such articles.I would love to learn form your article. Thanks.

    • DataFlair Team says:

      Hi Kiran,
      We are glad our loyal reader like our Java tutorial for method overriding. Our team continuously works to provide important and relevant information for the reader.
      Please share and suggest this blog with your peer groups.
      Regards,
      DataFlair

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.