The Wayback Machine - https://web.archive.org/web/20240921073600/https://www.geeksforgeeks.org/can-override-private-methods-java/
Open In App

Can we override private methods in Java?

Last Updated : 17 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let us first consider the following Java program as a simple example of Overriding or Runtime Polymorphism.

Java
class Base {
  public void fun() {
     System.out.println("Base fun");     
  }
}
  
class Derived extends Base {
  public void fun() {  // overrides the Base's fun()
     System.out.println("Derived fun");     
  }
  public static void main(String[] args) {
      Base obj = new Derived();
      obj.fun();
  }  
}

The program prints “Derived fun”. 
The Base class reference ‘obj’ refers to a derived class object (see expression “Base obj = new Derived()”). When fun() is called on obj, the call is made according to the type of referred object, not according to the reference. 

Is Overriding possible with private methods? 
Predict the output of the following program. 

Java
class Base {
  private void fun() {
     System.out.println("Base fun");     
  }
}
  
class Derived extends Base {
  private void fun() {
     System.out.println("Derived fun");     
  }
  public static void main(String[] args) {
      Base obj = new Derived();
      obj.fun();
  }  
}

We get compiler error “fun() has private access in Base” (See this). So the compiler tries to call base class function, not derived class, means fun() is not overridden.

An inner class can access private members of its outer class. What if we extend an inner class and create fun() in the inner class? 
An Inner class can access private members of its outer class, for example in the following program, fun() of Inner accesses private data member msg which is fine by the compiler.

Java
// Java program to demonstrate whether we can override private method 
// of outer class inside its inner class 
class Outer {
     private String msg = "GeeksforGeeks";
     private void fun() {
          System.out.println("Outer fun()");
     }

     class Inner extends Outer {
         private void fun()  {
               System.out.println("Accessing Private Member of Outer: " + msg);
         }
     }

     public static void main(String args[])  {

          // In order to create instance of Inner class, we need an Outer 
          // class instance. So, first create Outer class instance and then
          // inner class instance.
          Outer o = new Outer();
          Inner  i   = o.new Inner();
          
          // This will call Inner's fun, the purpose of this call is to 
          // show that private members of Outer can be accessed in Inner.
          i.fun();  

          // o.fun() calls Outer's fun (No run-time polymorphism).
          o = i; 
          o.fun();
     }
}

// Class 1 // Outer2 class 
class Outer2 { 
    // Method 1 
      // Private method of outer class 
    private void privateMethod() { 
        System.out.println("Private method in outer class"); 
    } 

    // Class 2 
      // Inner class 
    class Inner { 
        // Method 1 
          // Note: This will not be overriding private method of outer class 
        private void privateMethod() { 
            System.out.println("Private method in inner class"); 
        } 

        // Method 2 
          // Public method inside inner class 
        public void callPrivateMethod() { 
            // Calling private method of inner class 
            privateMethod(); 
        } 
    } 

    // Method 3 
      // Main driver method 
    public static void main(String[] args) { 
        // Creating object of outer and inner classes 
          // inside main() method 
        Outer2 outer = new Outer2(); 
        Outer2.Inner inner = outer.new Inner(); 
        inner.callPrivateMethod(); 
    } 
}

Output: 

Accessing Private Member of Outer: GeeksforGeeks
Outer fun()

In the above program, we created an outer class and an inner class. We extended Inner from Outer and created a method fun() in both Outer and Inner. If we observe our output, then it is clear that the method fun() has not been overridden. It is so because private methods are bonded during compile time and it is the type of the reference variable – not the type of object that it refers to – that determines what method to be called.. As a side note, private methods may be performance-wise better (compared to non-private and non-final methods) due to static binding.

Comparison With C++ 

1) In Java, inner Class is allowed to access private data members of outer class. This behavior is same as C++ (See this). 
2) In Java, methods declared as private can never be overridden, they are in-fact bounded during compile time. This behavior is different from C++. In C++, we can have virtual private methods (See this). 



Previous Article
Next Article

Similar Reads

Can we Overload or Override static methods in java ?
Let us first define Overloading and Overriding. Overriding: Overriding is a feature of OOP languages like Java that is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in the superclass (or base class). The implementation to be executed is decided at run-time and a decision is made accor
5 min read
Can We Override Default Method in Java?
Default method in Java is a method in java which are defined inside the interface with the keyword default is known as the default method. It is a type of non-abstract method. This method is capable of adding backward capability so that the old interface can grasp the lambda expression capability. Java Interface Default method is also known as Defe
3 min read
Can We Override Final Method in Java?
A method in a subclass is said to Override a method in its superclass if that method has a signature identical to a method in its superclass. When this method is called by an object of the subclass, then always the Overridden version will be called. In other words, the method which was Overridden in the superclass will become hidden. The JVM has 2
3 min read
private vs private-final injection of dependency
Dependency Injection (DI) is essential for improving code modularity, maintainability, and testability in the context of sophisticated Java programming. Choosing between private and private-final injection for dependencies is a typical DI concern. We will examine the distinctions between these two strategies in this post, as well as their applicati
5 min read
How to overload and override main method in Java
How to overload main method in java? Method Overloading can be defined as a feature in which a class can have more than one method having the same name if and only if they differ by number of parameters or the type of parameters or both, then they may or may not have same return type. Method overloading is one of the ways that java support Polymorp
4 min read
finalize() Method in Java and How to Override it?
The Java finalize() method of Object class is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection to perform clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection, or we can say res
2 min read
Private Methods in Java 9 Interfaces
Java 9 onwards, you can include private methods in interfaces. Before Java 9 it was not possible. Interfaces till Java 7 In Java SE 7 or earlier versions, an interface can have only two things i.e. Constant variables and Abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface. // Java 7 progr
4 min read
Private and final methods in Java
When we use final specifier with a method, the method cannot be overridden in any of the inheriting classes. Methods are made final due to design reasons. Since private methods are inaccessible, they are implicitly final in Java. So adding final specifier to a private method doesn't add any value. It may in-fact cause unnecessary confusion. class B
1 min read
Why to Override equals(Object) and hashCode() method ?
Prerequisite - Equals and Hashcode method HashMap and HashSet use the hashcode value of an object to find out how the object would be stored in the collection, and subsequently hashcode is used to help locate the object in the collection. Hashing retrieval involves: First, find out the right bucket using hashCode(). Secondly, search the bucket for
6 min read
Why Enum Class Can Have a Private Constructor Only in Java?
Every enum constant is static. If we want to represent a group named constant, then we should go for Enum. Hence we can access it by using enum Name. Enum without a constructor: enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } Enum with a constructor: enum Size { SMALL("The size is small."), MEDIUM("The size is medium."),
2 min read
Static methods vs Instance methods in Java
In this article, we are going to learn about Static Methods and Instance Methods in Java. Java Instance MethodsInstance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class in which the method is defined. public void geek(String name) {
5 min read
Why can't static methods be abstract in Java?
In Java, a static method cannot be abstract. Doing so will cause compilation errors.Example: Java Code // Java program to demonstrate // abstract static method import java.io.*; // super-class A abstract class A { // abstract static method func // it has no body abstract static void func(); } // subclass class B class B extends A { // class B must
3 min read
Can We Have Multiple Main Methods in Java?
Java is an object-oriented language all processing is carried within classes. Execution of a program means dictates java virtual machine to load the class and then start execution of its main method. Java's main method is entry point of any Java program. Public access modifier is used before the main method so that JVM can identify the execution po
4 min read
Public vs Private Access Modifiers in Java
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access mo
3 min read
Public vs Protected vs Package vs Private Access Modifier in Java
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access mo
7 min read
Package vs Private Access Modifiers in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access mo
3 min read
Private vs Final Access Modifier in Java
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access modi
3 min read
Protected vs Private Access Modifiers in Java
Access modifiers are those elements in code that determine the scope for that variable. As we know there are three access modifiers available namely public, protected, and private. Let us see the differences between Protected and Private access modifiers. Access Modifier 1: Protected The methods or variables declared as protected are accessible wit
2 min read
Private vs Protected vs Final Access Modifier in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access mo
5 min read
Private Constructors and Singleton Classes in Java
Let's first analyze the following question: Can we have private constructors ? As you can easily guess, like any method we can provide access specifier to the constructor. If it's made private, then it can only be accessed inside the class. Do we need such 'private constructors ' ? There are various scenarios where we can use private constructors.
2 min read
How to call private method from another class in Java with help of Reflection API?
We can call the private method of a class from another class in Java (which is defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private methods of different classes we will use Reflection API. To call the private method, we will u
3 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.io.BufferedWriter class methods in Java
Bufferreader class writes text to character-output stream, buffering characters.Thus, providing efficient writing of single array, character and strings. A buffer size needs to be specified, if not it takes Default value. An output is immediately set to the underlying character or byte stream by the Writer.Class Declaration public class BufferedWri
5 min read
Utility Methods of Wrapper Classes in Java
Prerequisite: Wrapper Classes The objective of the Wrapper class is to define several utility methods which are required for the primitive types. There are 4 utility methods for primitive type which is defined by the Wrapper class: 1. valueOf() method: We can use the valueOf() method to create a Wrapper object for a given primitive or String. There
4 min read
BigInteger max() and min() Methods in Java
Prerequisite: BigInteger Basics BigInteger max() method: The max() method of the BigInteger returns the BigInteger whose value is the greater between current BigInteger and BigInteger passed as a parameter to the method. If both the values are equal, either may be returned. There is a similar method compareTo() available on BigInteger class. The ma
3 min read
Green vs Native Threads and Deprecated Methods in Java
A multi-threaded process as we all know has several sequences of control, where each sequence is governed by a thread and is capable of performing independent tasks concurrently. In Java, multithreading concept is implemented by using the following two models. Green Thread model Native Thread Model Green Thread Model In this model, threads are comp
5 min read
FloatBuffer get() methods in Java with Examples
get() The get() method of java.nio.FloatBuffer Class is used to reads the float at the given buffer's current position, and then increments the position. Syntax : public abstract float get() Return Value: This method returns the float value at the buffer's current position. Throws: This method throws BufferUnderflowException - If the buffer's curre
5 min read
FloatBuffer put() methods in Java with Examples
put(float f) The put(float f) method of java.nio.FloatBuffer Class is used to write the given float into the newly created float buffer at the current position, and then increments the position. Syntax : public abstract FloatBuffer put(float f) Parameters: This method takes the float value f as a parameter which is to be written in float buffer. Re
6 min read
LongBuffer get() methods in Java
get() The get() method of java.nio.LongBuffer Class is used to read the Long at the given buffer's current position, and then increment the position. Syntax : public abstract Long get() Return Value: This method returns the Long value at the buffer's current position. Throws: This method throws BufferUnderflowException - If the buffer's current pos
5 min read
IntBuffer get() methods in Java | Set 1
get() The get() method of java.nio.IntBuffer Class is used to reads the int at the given buffer's current position, and then increments the position. Syntax : public abstract int get() Return Value: This method returns the int value at the buffer's current position. Throws: This method throws BufferUnderflowException - If the buffer's current posit
5 min read
Article Tags :
Practice Tags :