In this tutorial, we will learn about the Final Keyword in Java in Java. How to use them with the help of examples.
Define Final Keyword in Java
The final keyword is use for making data, method and class as constant. Final keyword is use to denote constants. Once any entity is declare final, it can be assign only once.
The following are different contexts where final is use
- Variable
- Method
- Class
Variable
When we use final keyword with data declaration then the data will be constant it means we cannot increase or decrease the data.
Example of Variable in Final Keyword
Let’s run the code
Method
When we use final keyword with method then method become constant. It means final method cannot be override.
Example of Method in final keyword
Let’s run the code
Class
When we use final keyword with class then class became constant and this class cannot be extends using extends keyword with other class (derived class) (final class cannot be inherited).
Example of Class in Final Keyword
Let’s run the code
Method Overloading in Java
Method Overloading allows different methods to have the same name, but different parameters is know as overloaded methods. This feature is know as method overloading. Method Overloading is not possible by changing the return type of the method only.
There are two overload the method
- Changing number of arguments
- Changing the data type
Changing number of arguments
Example
Input Value
Example of Changing number of argumentsclass Main { static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} } class abms{ public static void main(String[] args){ System.out.println(Main.add(33,44)); System.out.println(Main.add(55,66,77)); } }
Changing the data type
Example
Input Value
Example of Changing the data typeclass Main { static int add(int a, int b){return a+b;} static double add(double a, double b){return a+b;} } class abms{ public static void main(String[] args){ System.out.println(Main.add(15,15)); System.out.println(Main.add(18.52,18.85)); } }
Let’s run the code
Output Value
If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.
To know more about JAVA Wikipedia please click here .
Stay Connected Stay Safe, Thank you
0 Comments