Friday, March 24, 2023

Can You Override Private Method in Java? Inner Class?

No, you cannot override private methods in Java, private methods are non-virtual in Java and access differently than non-private one. Since method overriding can only be done on derived class and private methods are not accessible in a subclass, you just can not override them. By the way, one more possibility of overriding private methods in an inner class, since private methods are accessible in an inner class, and that’s why it is one of the tricky java interview questions. Anyway, this will also not work because private methods are bonded during compile time and only Type (or Class) is used to locate a private method.

For Example in below code where it looks like that nested class is an overriding private method, but if you call privateMethod() with a type of super class but the object of the subclass, it will only execute privateMethod() declared in the parent class, which is not exactly method overriding. 

Had the private method overridden that it would have called method from child class. By the way, compiler will not complain, it will treat method with exact same signature in child class as separate method, and this is known as method hiding in Java.


Should You Make Private method Final in Java?

This is another common doubt among Java programmers, using final and private method in Java is a good choice, but I don't think it offer any benefit in terms of performance. Rather, this decision should be taken on the basis of design, functionality and ensuring readability of code. 

Since making a method final,  just limit it’s ability to be overridden, it doesn't make much sense to mark a private method as final in Java, because private method can not overridden in Java by any means. So compiler will definitely perform sort of optimization it can e.g. inlining or caching it. 

By the way, private keyword is one of the fundamental access modifier and can be applied to variables, methods and class, let’s see some of the worth knowing fact about private keyword in Java

Can You Override Private Method in Java? Inner Class?



Important Points about private keyword in Java


1. You can apply private access modifier fields, methods and any inner class in Java. It’s most restricted access modifier and only accessible in the class they are declared. They are not visible outside the class and accessing them outside will result in compile time error.

2.Top level Classes can not be private in Java. They can only be either public or without any access modifier i.e. only accessible in the package they are declared. In case of public class, name of Java source file must match with the name of public class.

3.Though private methods or variables are not accessible outside of  the class, they are declare. They can be accessed via reflection by using setAccessible(true) and changing there private visibility. See this article for more details.

4.As we have seen in this article, private methods can not be overridden in Java, not even inside nested or inner classes.

5.Private members runs faster than non-private one, because of static binding. They are also better candidate for optimization from compiler because they can not be overridden.

Can private method be overridden in Java



Private Method Overriding Example

In order to prove theory, we must see an example. In this Java program, we have declared a private method and trying to override them inside an Inner class. In main method, we are calling private method by using reference variable of Outer class, which is also parent but pointing to object of sub class.  

Though it does show that private method is accessible in Inner class, you just can not override them. Let’s see what does output shows.

/**
  * Java Program to demonstrate, private method can not be overridden in Java, 
  * not even on Inner classes. Main reason of that behavior is because they are bonded 
  * using static binding in Java.
  */

 public class PrivateMemberExample {

    private String i_m_private = "I am private member, not accessible outside this Class";

    private void privateMethod() {
        System.out.println("Private method of Outer Class");
    }

    public static void main(String args[]) {
        PrivateMemberExample outerClass = new PrivateMemberExample();
        NestedClass nc = outerClass.new NestedClass();
        nc.showPrivate(); //shows that private method are accessible in inner class.
       
        outerClass = nc;
        outerClass.privateMethod(); // This will not call private method from inner class,
                                    // which shows you can not override 
                                    // private method inside inner class. 
    }

    class NestedClass extends PrivateMemberExample {

        public void showPrivate() {
            System.out.println("Accessing Private members of Outer class: " + i_m_private);
            privateMethod();
        }
       
       /*
        * private method trying to be overridden, 
        * instead it’s just hiding parent class method.
        */
        private void privateMethod() {
             System.out.println("Private method of Nested Class");
         }
    }
}


Output
Accessing Private members of Outer class: I am private member, not accessible outside this Class
Private method of Outer Class
Private method of Outer Class
 
From the output, it’s clear that both the call to private method, which is made by using reference variable with the type of parent class result in invoking private method from the parent class, which is also an outer class in our case. 

Had it was overridden, in case of second call, which is made using object of Inner sub class, would result in execution of private method of nested class. This proves that private method can not be overridden in Java, not in sub class and not even in Inner class.

That's all about question, Can we override private method in Java?. We have learned that this is not possible in Java. Though this is a real tough Java question, especially follow-up question which involves, Can we override private method on Inner class in Java. It can confuse you, if you are not sure about how private methods are bonded in Java. Let me know, if you think otherwise.


Related Java Interview questions  from Java67 Blog

Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

8 comments:

  1. But I am getting the below output:
    Accessing Private members of Outer class: I am private member, not accessible outside this Class
    Private method of Nested Class
    Private method of Nested Class

    ReplyDelete
  2. Change nc.privateMethod(); to outerClass.privateMethod(); The output will be:-
    Accessing Private members of Outer class: I am private member, not accessible outside this Class
    Private method of Nested Class
    Private method of Outer Class

    ReplyDelete
    Replies
    1. I think there are some points, which should have been much clear :

      1) if first call to showPrivate() method is to demonstrate that private method of Outer class is accessible inside Inner class, than you have to first comment out privateMethod() of NestedClass, which is hiding privateMethod of Outer class. If you do this, than you will get the output :

      Accessing Private members of Outer class: I am private member, not accessible outside this Class
      Private method of Outer Class

      I think, that's what author meant to, by looking at code and output.

      Now, In second call to private method, which should be outClass.privateMethod(), you need to uncomment privateMethod() in nested class. Now this is what he means by trying to override a private method in Inner class. If you run the code again, you will get output as

      Private method of Outer Class

      I hope this make sense.

      Delete
  3. Also @Override annotation will show error instead of hiding the private method

    ReplyDelete
  4. You cleared my doubt regarding private class! nice site!

    ReplyDelete
  5. Confusing explanation of the example :)

    ReplyDelete
    Replies
    1. Hello Squeerzer, I agree its not easy to catch because of reference of inner and outer class, but let me know if you are not able to understand the example and the concept behind overriding private method, I'll try to explain you here. Let me know your doubt

      Delete
  6. awesome explanation thanks.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.