×

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

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.