×

Method Overriding in Java

Overriding 

Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods.

Method Overriding

Method Overriding is a phenomenon that occurs when there are two or more methods with the same method name with the same parameters but in different classes. They are parent class and child class. Method overriding can be applied only in the inheritance concept. Method overriding is also known as run time polymorphism.

Example:

class Parent
{
void add (int x)
}
class Child
{
void add(int x)
}

   Here in the above example, the method "add()" has the same method name and same parameters and is present in both parent class and child class.

Ways for Method Overriding

Method overriding can be done by having

  1. The method in both parent class and child class should have the same name and the same number of parameters.
  2. The method in both parent class and child class should also have the same return type.
  3. Method overriding is prevented in both final and static methods.

Advantages of Method Overriding in Java

  1. We can implement the same method multiple times.
  2. We can also invoke the parent class method without creating the object using the super keyword.
  3. Super keyword used to access the method from child class to parent class without creating an object for the parent class.
  4. It also improves the readability of the source code.
  5. It also defines the behavior of the class.

Disadvantages of Method Overriding

  1. We can’t override the private, static and final methods.
  2. We can’t override a method outside the package.
  3. We cannot reduce the visibility of the overridden method.
  4. We can’t override a method if the classes are not in inheritance.

Some Points on Method Overriding

  1. Method overriding is also known as run time polymorphism.
  2. Method overriding has the same method name with the same parameters and same return type in different classes, that is, parent class and child class.
  3. Method overriding is used to implement the method in the parent class using the super keyword.
  4. Method overriding occurs in two classes that have an inheritance relationship.
  5. Method overloading gives better performance as compared to method overriding.
  6. We cannot override final and private methods.

Example program on method overloading:

//Program to implement method overriding in java
import java .io.*;
import java .lang.*;
importjava.util.*;
class KK // parent class
{
void display(int x) // dispaly method in parent class
{
System.out.println(" Welcome to parent class: ");
    // printing the square root of the argument passed
System.out.println(" square root of x is = "+ Math.sqrt(x));
} // display
} // KK
class R extends KK
{
void display(int x) // display method inchild class
{
System.out.println(" Welcome to child class: ");
    // printing the square value of the argument passed
System.out.println(" square value of x is = "+ (x*x));
} // display
} // R


classHelloWorld // class with main
{
public static void main(String[] args) // main method
    {
        // creating object for Scanner class which is present utill package
        Scanner sc = new Scanner(System.in);
System.out.println("Hello, World!");
System.out.println(" Enter the number: ");
int x = sc.nextInt(); // reading the input
        R r1 = new R() ; // object creation for R class
        r1.display(x); // calling display method
        KK k1 = new KK(); // object creation for KK class
        k1.display(x); // calling display method
    } // main
} // HelloWorld

Output:

Method Overriding in Java

In the above Program, we have created a method "display()" in both parent class and child class with the same parameters and same return type. We have created objects for both parent class and child class and have passed the parameters. So that we can perform different operations as shown above in the Program. Here we have imported the lang package to access the "Math.sqrt()" function to find the square value. Hence we can see the output of the Program.

Ways for Preventing Method Overriding

  1. By declaring the overriding method using the final keyword(Ex: final void display()).
  2. By using the static method rather than non-static method.
  3. By using the privet access modifier in the overriding method.
  4. By using the default access modifier in the overriding method.

Example Program to Prevent Method Overriding

1. By using the final keyword:

The final keyword is used to stop inheritance. If the classes or not an inheritance, we can’t perform method overriding.

//Program to prevent method overriding using final keyword:
import java .io.*;
import java .lang.*;
importjava.util.*;
class KK // parent class
{
final void display(int x) // Final method
{
System.out.println(" Welcome to parent class: ");
    // printing the square root of the argument passed
System.out.println(" square root of x is = "+ Math.sqrt(x));
} 
} 
class R extends KK // child class
{
void display(int x) // display method inchild class
{
System.out.println(" Welcome to child class: ");
    // printing the square value of the argument passed
System.out.println(" square value of x is = "+ (x*x));
} // display
} // R


classHelloWorld // class with main
{
public static void main(String[] args) // main method
    {
        // creating object for Scanner class which is present utill package
        Scanner sc = new Scanner(System.in);
System.out.println("Hello, World!");
System.out.println(" Enter the number: ");
int x = sc.nextInt(); // reading the input
        R r1 = new R() ; // object creation for R class
        r1.display(x); // calling display method
        KK k1 = new KK(); // object creation for KK class
        k1.display(x); // calling display method
    } 
}

In this Program, we declared the method in the parent class using the final keyword. The parent class method gets overridden, but we can override the final method, so the output of the Program should be an error, and the overridden method is final.

Output:

Method Overriding in Java

2. By using private access modifier:

Access modifiers are used to define the scope of the method or variables. If we define a method using private access, the scope of the method will be only within the class, and we can't access that method outside the class. Without accessing the method, we can't override a method.

//Program to prevent method overriding using private access modifier
import java .io.*;
import java .lang.*;
importjava.util.*;
class KK // parent class
{
private void display(int x) // Static method
{
System.out.println(" Welcome to parent class: ");
    // printing the square root of the argument passed
System.out.println(" square root of x is = "+ Math.sqrt(x));
}
} 
class R extends KK // child class
{
void display(int x) // display method inchild class
{
System.out.println(" Welcome to child class: ");
    // printing the square value of the argument passed
System.out.println(" square value of x is = "+ (x*x));
} // display
} // R


classHelloWorld // class with main
{
public static void main(String[] args) // main method
    {
        // creating object for Scanner class which is present utill package
        Scanner sc = new Scanner(System.in);
System.out.println("Hello, World!");
System.out.println(" Enter the number: ");
int x = sc.nextInt(); // reading the input
        R r1 = new R() ; // object creation for R class
        r1.display(x); // calling display method
        KK k1 = new KK(); // object creation for KK class
        k1.display(x); // calling display method
    } 
}

Output:

Method Overriding in Java

In this Program, we declared a method using a private access modifier, so the scope of the method is within the class, so we can't access the method from another class. Thereby we can't override the method. So we get an error.

3. By using the static method

Another method to prevent method overriding is using the static method. If we declare a static method, it will become a class method rather than an object method, and we can't override the class methods.

//Program to prevent method overriding using static method rather than non-static 
// method:
import java .io.*;
import java .lang.*;
importjava.util.*;
class KK // parent class
{
static void display(int x) // Static method
{
System.out.println(" Welcome to parent class: ");
    // printing the square root of the argument passed
System.out.println(" square root of x is = "+ Math.sqrt(x));
}
} 
Class R extends KK // child class.
{
void display(int x) // display methodinchild class
{
System.out.println(" Welcome to child class: ");
    // printing the square value of the argument passed
System.out.println(" square value of x is = "+ (x*x));
} // display
} // R


classHelloWorld // class with main
{
public static void main(String[] args) // main method
    {
// creating object for Scanner class which is present utill package
        Scanner sc = new Scanner(System.in);
System.out.println("Hello, World!");
System.out.println(" Enter the number: ");
int x = sc.nextInt(); // reading the input
        R r1 = new R() ; // object creation for R class
        r1.display(x); // calling display method
        KK k1 = new KK(); // object creation for KK class
        k1.display(x); // calling display method
    } 
}

In this Program, we declared a method in the parent class using the static keyword. If a method s declared a method using a static keyword, it will become a class method rather than an object method, and we can’t override a class method, so the output should be an error and we can’t override a static method.

Output:

Method Overriding in Java

4. By using the default access modifier in the overriding method.

This is only possible when the access of the overridden method is within the package but not outside the package. To obtain this situation, we have to declare the parent class method using private and child class with default access modifier.

//Program to prevent method overriding using default access modifier
import java .io.*;
import java .lang.*;
importjava.util.*;
class KK // parent class
{
private void display(int x) // Static method
{
System.out.println(" Welcome to parent class: ");
    // printing the square root of the argument passed
System.out.println(" square root of x is = "+ Math.sqrt(x));
}
} 
class R extends KK // child class
{
default void display(int x) // display method inchild class
{
System.out.println(" Welcome to child class: ");
    // printing the square value of the argument passed
System.out.println(" square value of x is = "+ (x*x));
} // display
} // R


classHelloWorld // class with main
{
public static void main(String[] args) // main method
{
        // creating object for Scanner class which is present utill package
        Scanner sc = new Scanner(System.in);
System.out.println("Hello, World!");
System.out.println(" Enter the number: ");
int x = sc.nextInt(); // reading the input
        R r1 = new R() ; // object creation for R class
        r1.display(x); // calling display method
        KK k1 = new KK(); // object creation for KK class
        k1.display(x); // calling display method
    } 
}

Output:

Method Overriding in Java

We can access the parent class method from the child class using the super keyword.

//Program to access parent class method from child class
import java .io.*;
import java .lang.*;
importjava.util.*;
class KK // parent class
{
void display(int x) 
 {
System.out.println(" Welcome to parent class: ");
    // printing the square root of the argument passed
System.out.println(" square root of x is = "+ Math.sqrt(x));
}
} 
Class R extends KK // child class.
{
void display(int x) // display method inchildclass
{
System.out.println(" Welcome to child class: ");
    // printing the square value of the argument passed
System.out.println(" square value of x is = "+ (x*x));
super.display(x); // calling parent class method
} // display
} // R


classHelloWorld // class with main
{
public static void main(String[] args) // main method
    {
        // creating object for Scanner class which is present utill package
        Scanner sc = new Scanner(System.in);
System.out.println("Hello, World!");
System.out.println(" Enter the number: ");
int x = sc.nextInt(); // reading the input
        R r1 = new R() ; // object creation for R class
        r1.display(x); // calling display method
    } 
}

Output:

Method Overriding in Java

Conclusion

In this article, we discussed method overriding in java and rules to perform method overriding. We discussed how to prevent method overriding. We executed the programs on method overriding and prevention of method overriding. We discussed the advantages and disadvantages of method overriding.


Related Topics

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.