×

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not.

Override in Java

Any object-oriented programming language has a feature called overriding that enables a subclass or child class to provide a specific implementation of a function that is already provided by one of its super-classes or parent classes. When two methods have the same name, identical parameters or signature, and identical return type, the replacement method is referred to as a "override" method (or sub-type).

Method overriding is one technique Java uses to establish Run Time Polymorphism. The object that calls a method will determine which version of the method is executed. When a method is called from an object of a parent class, the method's parent class version is executed; however, when a method is called from an object of a subclass, the child class version is executed. In other words, the version of an overridden method that is run depends on the type of the object being referenced, not the type of the reference variable.

Private Method

Private methods in Java are those that have the private access modifier, are restricted to access in the defining class only, and are not visible in their descendant class as a result. As a result, they are ineligible to be overridden. The same method can be defined in the child class and accessed in the parent class, though. A method cannot be overridden in any of the classes that are inheriting it when the final specifier is used. Methods are finalized for design purposes.

Private methods are final in Java by default because they cannot be accessed. In light of this, adding a final specifier to a private method is of no benefit. In fact, it might lead to needless misunderstanding.

Can We Override Private Method in Java?

No, with Java we cannot override static or private methods.

Java's private methods are only accessible to the class in which they are declared, limiting their use to that class. Java does not allow overriding of static or private methods.

The super class method will be hidden if an identical method with the same return type and method arguments is created in a child class; this is referred to as method hiding. Like how you cannot access a private method in a subclass, you also cannot override it. What you can do is add a second, identical private method to the child class. Let's look at the example below so that we can better grasp it.

Example:

class Par {
   private void disp() {
      System.out.println("class is super calss");
   }
}
public class Example extends Parent {
   void disp() // here trying to override disp() {
      System.out.println("Class is sub class");
   }
   public static void main (String [] s) {
      Par ob = new Ex ();
Ob.disp();
   }
}

Output:

Ex.java:17: error: disp () has access of private in Parent
obj. method ();
      ^
1 error

The application displays an error at compilation time indicating that display () in the Parent class has private access and cannot be overridden in the subclass Example.

A method is a member of a class rather than the class's object if it is specified as static. It may be called without first producing a class object. A static method can also access the class's static data elements.

Example 2:

class Par {
   static void disp() {
      System.out.println("class is a Super class");
   }
}
public class Example extends Parent {
   void disp () // trying to override display () {
      System.out.println("Class is asub class");
   }
   public static void main (String [] s) {
      Par ob = new Ex ();
      ob.Disp();
   }
}

Output:

Example.java:10: error: display () in Example given cannot override display () in Parent
void display () // trying to override display ()
    ^
The method overridden is static
1 error

We established an outer class and an inner class in the software. We added a function disp () to both Outer and Inner, which is an extension of Outer. It is obvious that the method disp () has not been overridden if we look at our output.

This is the case because private methods are bound together at compile time, and the method that is called depends on the type of the reference variable rather than the type of the object it refers to. In addition, because of static binding, private methods may perform better than non-private and non-final methods.


Related Topics

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Java Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type....

3 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

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