Method Overriding in Java – Overridden Methods in Java

1. Objective

In our last chapter, we learned Polymorphism in Java. Here, we start a new chapter called Method Overriding in Java, in which we will focus on rules for Java method overriding, multilevel method-overriding in Java with examples and discuss a brief on method overriding vs overloading in Java.

So, let’s start Method Overriding in Java.

What is Method Overriding in Java

Method Overriding in Java – Overridden Methods in Java

2. What is 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 which is already used by parent class 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.

Do you know how to declare and call methods in Java?

Method Overriding in Java - Overridden Methods in Java

Method Overriding in Java – Overridden Methods in Java

3. Method Overriding in Java

Java 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 java object and not on the type of reference variable.

A program to demonstrate 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
              @Override
              void show()
                    {
                       System.out.println("Child's show()"
                   );
             }
// Driver class
class Main
       {
            public static void main(String[] args)
                    {
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
                         Parent obj1 = new Parent();
                         obj1.show();
// If a Parent type reference refers
// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
                        Parent obj2 = new Child();
                        obj2.show();
                   }
      }

Let’s explore the difference between Method Overloading vs Overriding in Java

4. Rules for Method Overriding in Java

a. Overriding and Java Access-Modifiers

This method allows more access than the overridden method, it is always more i.e. the access and never less than the overridden method.

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

Example 

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

b. Final Methods cannot be Overridden Methods in Java

When we don’t want the method to 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() {  }
            }

c. 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.

Method Overriding in Java

Method Overriding in Java

Follow this link to know more about Static methods in Java

Example 

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

d. Private Methods cannot be Overridden Method in Java

This is due to the fact that they bond at compile time, this is the reason we cannot override private methods.

e. 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.

f. 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 show()
               {
                    System.out.println("Parent's show()");
               }
      }
// Inherited class
class Child extends Parent
         {
// This method overrides show() of Parent
             @Override
             void show()
                  {
                    super.show();
                    System.out.println("Child's show()");
                  }
         }
// Driver class
class Main
     {
         public static void main(String[] args)
             {
                 Parent obj = new Child();
                 obj.show();
             }
     }

g. Overriding and 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.

h. Overriding and Exception-Handling in Java

There are two rules that are to be kept in mind while handling exceptions in java.
a. Rule 1 – Throwing a checked expression causes a compile-time error. If the superclass doesn’t throw any exception then the subclass can.
Example 

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

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

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

i. Overriding and Abstract Method in Java

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

j. Overriding and Synchronized/Stricfp Method in Java

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

See Also-  Types of Exceptions in Java

5. 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
class Main
     {
         public static void main(String[] args)
              {
                   Parent obj1 = new GrandChild();
                   obj1.show();
              }
     }

6. Method Overriding vs. Overloading in Java

Method Overloading in Java is when a method has a different signature, while in method overriding it is the same method having the same signature but with different classes and they connect through inheritance.
Overloading supports compile-time polymorphism while overriding supports run-time polymorphism.

Java Quiz

Java Method Overriding vs. Overloading

Java Method Overriding vs. Overloading

So, this was all about Method Overriding in Java. Hope you like our explanation.

7. Conclusion

Hence,  we studied what is method overriding in Java, its different types with which it can incorporate and how it be multi-level too. At last, we discuss the difference between Java method overloading vs overriding in Java. This helped us understand the runtime polymorphism in Java better and also help us understand its relation to inheritance in Java.

See also-

Java Strings and Java Array

For reference

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 *