• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

What is Method Overriding in Java

July 10, 2015 by javainterviewpoint Leave a Comment

When a Sub class has the implementation of the same method which is defined in the Parent class then it is called as Method Overriding. Unlike Method Overloading in Java the parameters passed will not differ in Overriding. Lets now look in how to Override a method in Java.

Lets take the below example we have two classes Parent and Child, where Child extends Parent.

Parent.java

package com.javainterviewpoint;

public class Parent 
{
    public void display(String name)
    {
        System.out.println("Welcome to Parent Class \""+name+"\"");
    }
    public void disp()
    {
        System.out.println("disp() method of Parent class");
    }
}

In the Parent class we have two method display() and disp() nothing else.

Child.java

package com.javainterviewpoint;

public class Child extends Parent
{
    public void display(String name)
    {
        System.out.println("Welcome to Child Class \""+name+"\"");
    }
    public void show()
    {
        System.out.println("show() method of Child class");
    }
    public static void main(String args[])
    {
        //Create object for the parent class 
        Parent p = new Parent();
        //Calling parent class methods
        p.display("JavaInterviewPoint");
        p.disp();
        
        //Creating object for the child class
        Child c = new Child();
        c.display("JavaInterviewPoint");
        c.show();
    }
}

Child class extends the Parent class and overrides the display() method and has its own method show(). In the main() method we will be creating objects for both Parent and Child class and their individual methods are called.
When we run the above code we will get the below output

Welcome to Parent Class "JavaInterviewPoint"
disp() method of Parent class
Welcome to Child Class "JavaInterviewPoint"
show() method of Child class

The above example represents the simple Overriding technique where we create the objects for individual class and call the correspoding methods.

Role of Access Modifiers in Overriding

The access modifier of the overriding method(method in the Child class) cannot be more restrictive than the Parent class. Lets take below example where we have the display() method with access modifier as “public” in Parent class and the Child class cannot have “private” or “protected” or “default” modifiers as all of them are more restrictive than “public”

class Parent 
{
    public void display(String name)
    {
        System.out.println("Welcome to Parent Class \""+name+"\"");
    }
}
public class Child extends Parent
{
    private void display(String name)
    {
        System.out.println("Welcome to Child class \""+name+"\"");
    }
    public static void main(String args[])
    {
        //Create object for Child class
        Child c = new Child();
        c.display("JIP");
        
        //Create object for Parent class will work here
        Parent p = new Parent();
        p.display("JIP");
     }
}

when you run the above code then you will get compilation error “Cannot reduce the visibility of the inherited method from Parent”. But when the Parent is more restrictive than Child class then it is allowed, lets see that too

package com.javainterviewpoint;

class Parent 
{
    protected void display(String name)
    {
        System.out.println("Welcome to Parent Class \""+name+"\"");
    }
}
public class Child extends Parent
{
    public void display(String name)
    {
        System.out.println("Welcome to Child class \""+name+"\"");
    }
    public static void main(String args[])
    {
        //Create object for Child class
        Child c = new Child();
        c.display("JIP");
        
        //Create object for Parent class
        Parent p  = new Parent();
        p.display("JIP");
     }
}

The above code runs fine without any exception as the Child class method is less restrictive than the Parent class method.
output :

Welcome to Child class "JIP"
Welcome to Parent Class "JIP"

Use of Super keyword in Overriding

We can use the super keyword to call the Parent class method inside the Child class method. In the below code we have called the Parent class display() method from Child class.

package com.javainterviewpoint;

class Parent 
{
    public void display(String name)
    {
        System.out.println("Welcome to Parent Class \""+name+"\"");
    }
}
public class Child extends Parent
{
    public void display(String name)
    {
        System.out.println("Welcome to Child class \""+name+"\"");
        super.display("JIP");
    }
    public static void main(String args[])
    {
        //Create object for Child class
        Child c = new Child();
        c.display("JIP");
     }
}

Exception Handling in Overriding

Below are the rules which has to be followed when go for Method Overriding with Exception Handling.

  1. When Parent class method doesn’t throw any Exception then Child class overriden method also cannot declare any Checked Exception (Compile time Exception).
  2. When Parent class method doesn’t throw any exception then Child class overriden method can declare UnChecked Exception (Runtime Exception).
  3. When Parent class declares an Exception then the Child class overriden method can declare the same or sub class exception or no exception.
  4. When Parent class declares an Exception then the Child class overriden method  cannot declare super class exception

1. When Parent class method doesn’t throw any Exception then Child class overriden method also cannot declare any Checked Exception

package com.javainterviewpoint;

import java.io.IOException;

class Parent 
{
    public void display()
    {
        System.out.println("Welcome to Parent Class");
    }
}
public class Child extends Parent
{
    public void display() throws IOException
    {
        System.out.println("Welcome to Child class");
    }
    public static void main(String args[]) throws IOException
    {
        //Create object for Child class
        Child c = new Child();
        c.display();
        
        //Create object for Parent class
        Parent p = new Parent();
        p.display();
     }
}

Here we have the Parent Class display() method which doesn’t throw any exception and Child class has overriden the display() method and throws IOException. As IOException is a Checked Exception we cannot have it thrown and hence it will give the below exception.

Output :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Exception IOException is not compatible with throws clause in Parent.display()

	at com.javainterviewpoint.Child.display(Child.java:14)
	at com.javainterviewpoint.Child.main(Child.java:22)

2. When Parent class method doesn’t throw any exception then Child class overriden method can declare UnChecked Exception

package com.javainterviewpoint;

class Parent 
{
    public void display()
    {
        System.out.println("Welcome to Parent Class");
    }
}
public class Child extends Parent
{
    public void display() throws ArrayIndexOutOfBoundsException
    {
        System.out.println("Welcome to Child class");
    }
    public static void main(String args[]) throws ArrayIndexOutOfBoundsException
    {
        //Create object for Child class
        Child c = new Child();
        c.display();
        
        //Create object for Parent class
        Parent p = new Parent();
        p.display();
     }
}

The Parent Class display() method which doesn’t throw any exception and Child class has overriden the display() method and throws ArrayIndexOutOfBoundsException. As ArrayIndexOutOfBoundsException is a UnChecked Exception we can have it thrown and hence it will run without any issue.

Output :

Welcome to Child class
Welcome to Parent Class

3. When Parent class declares an Exception then the Child class overriden method can declare the same or sub class exception or no exception

package com.javainterviewpoint;

class Parent 
{
    public void display() throws ArrayIndexOutOfBoundsException
    {
        System.out.println("Welcome to Parent Class");
    }
}
public class Child extends Parent
{
    public void display() throws Exception
    {
        System.out.println("Welcome to Child class");
    }
    public static void main(String args[]) throws Exception
    {
        //Create object for Child class
        Child c = new Child();
        c.display();
        
        //Create object for Parent class
        Parent p = new Parent();
        p.display();
     }
}

The Parent Class display() method throws ArrayIndexOutOfBoundsException exception and Child class overriden display() method throws Exception.  We all know that Exception class is the super class of all Exceptions, we cannot have the Child class method throwing a Super class Exception while Parent class method throwing a Sub class exception and hence we will be getting the below exception when we run the above code.

Output :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Exception Exception is not compatible with throws clause in Parent.display()

	at com.javainterviewpoint.Child.display(Child.java:12)
	at com.javainterviewpoint.Child.main(Child.java:20)

4. When Parent class declares an Exception then the Child class overriden method  cannot declare super class exception

package com.javainterviewpoint;

class Parent 
{
    public void display() throws Exception
    {
        System.out.println("Welcome to Parent Class");
    }
}
public class Child extends Parent
{
    public void display() throws ArrayIndexOutOfBoundsException
    {
        System.out.println("Welcome to Child class");
    }
    public static void main(String args[]) throws Exception
    {
        //Create object for Child class
        Child c = new Child();
        c.display();
        
        //Create object for Parent class
        Parent p = new Parent();
        p.display();
     }
}

The Parent Class display() method throws Exception and Child class overriden the display() method and throws ArrayIndexOutOfBoundsException .  The Child class overriden method is allowed throw sub class exception, so the above code will run fine without any issue.

Output :

Welcome to Child class
Welcome to Parent Class

Other interesting articles which you may like …

  • JVM Architecture – Understanding JVM Internals
  • Object and Object Class in Java
  • Difference between JDK, JRE and JVM
  • Components of Java Development Kit (JDK)
  • What is a Class in Java with Example
  • How to open .class file in Java
  • How to Set Classpath for Java in Windows
  • ClassNotFoundException Vs NoClassDefFoundError
  • How HashMap works in Java
  • How to make a class Immutable in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of polymorphism in Java
  • Types of Inheritance in Java
  • Java does not supports Multiple Inheritance Diamond Problem?

Filed Under: Core Java, Java, OOPs, Polymorphism Tagged With: Dynamic Method Dispatch, Dynamic Method Dispatch Technique, Method Overriding, Method Overriding in Java, overriding, polymorphism, Polymorphism in Java, Runtime Polymorphism

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·