No, we cannot override the private methods because private methods will not be inherited to sub class.
Example
class SubtractionTest { private void subtraction(int num1, int num2) { System.out.println("Inside super class method"); System.out.println(num1 - num2); } } public class Main extends SubtractionTest { public static void main(String[] args) { Main main = new Main(); main.subtraction(150, 100); } } |
Example
Main.java:15: error: cannot find symbol main.subtraction(150, 100); ^ symbol: method subtraction(int,int) location: variable main of type Main 1 error |
Note: If we create the same method in subclass then JVM will consider it as a sub class method, not the overridden method.
Example
class SubtractionTest { private void subtraction(int num1, int num2) { System.out.println("Inside super class method"); System.out.println(num1 - num2); } } public class Main extends SubtractionTest { void subtraction(int num1, int num2) { System.out.println("Inside sub class method"); System.out.println(num1 - num2); } public static void main(String[] args) { Main main = new Main(); main.subtraction(150, 100); } } |
Example
Inside sub class method 50 |
Java interview questions on method overloading and overriding
- What is method overloading in java?
- Can we declare an overloaded method as static and another one as non-static?
- Can overloaded methods be synchronized?
- Synchronized override method
- Can we declare overloaded methods as final?
- Can overloaded method be overridden?
- What is method overriding in java?
- Can static method be overridden?
- Difference between method overloading and overriding in java?
- Can we override private methods in java?
- Is it possible to override non static method as static method?