Yes, we can declare overloaded methods as final.
class SumTest { public final void sum(int num1, int num2) { System.out.println(num1 + num2); } public void sum(int num1, int num2, int num3) { System.out.println(num1 + num2 + num3); } } public class Main { public static void main(String[] args) { SumTest sumTest = new SumTest(); sumTest.sum(10, 5); sumTest.sum(10, 5, 20); } } |
Output
15 35 |
Note: Final method can not be overridden. See the below example.
class SumTest { public final void sum(int num1, int num2) { System.out.println(num1 + num2); } public final void sum(int num1, int num2, int num3) { System.out.println(num1 + num2 + num3); } } public class Main extends SumTest { public void sum(int num1, int num2) { System.out.println(num1 + num2); } public static void main(String[] args) { SumTest sumTest = new SumTest(); sumTest.sum(10, 5); sumTest.sum(10, 5, 20); Main main = new Main(); main.show(); } } |
Output
Main.java:14: error: sum(int,int) in Main cannot override sum(int,int) in SumTest public void sum(int num1, int num2) { ^ overridden method is final Main.java:22: error: cannot find symbol main.show(); ^ symbol: method show() location: variable main of type Main 2 errors |
Note: A non final method can not be overloaded as well as overridden with final declaration.
class SumTest { public void sum(int num1, int num2) { System.out.println(num1 + num2); } public final void sum(int num1, int num2, int num3) { System.out.println(num1 + num2 + num3); } } public class Main extends SumTest { public final void sum(int num1, int num2) { System.out.println(num1 + num2); } public static void main(String[] args) { SumTest sumTest = new SumTest(); sumTest.sum(10, 5); sumTest.sum(10, 5, 20); Main main = new Main(); main.sum(10, 5); } } |
Output
15 35 15 |
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?