FINAL KEYWORD IN JAVA
Hey guys, today we will discuss about the final keyword in java. So what is
a final keyword? A final keyword can be used with variable initialisations,
writing methods and classes. So let's talk about each one of them separately.
i)Final variables
So final variables can be used when we have to initialise a variable in
java and don't want it's value to be messed anytime later in the code. That
means we cannot re-initialise a variable value that has already been
initialised in the code. Like for example, let's see what will happen if we
will try to mess up with the values of the variables already initialised (with
final keyword)
public class Coding_Winds {
public static void main(String[] args) {
final int x=5;
x=5; /* will give a compile time error:
the final local variable cannot be re-assigned */
}
}
Static keywords can also be used in the program with final keywords, for
example
public class Coding_Winds {
static final int x=5;
public static void main(String[] args) {
System.out.println("You can't change the value of the
variable x which is currently "+x);
}
}
/* Output:
You can't change the value of the variable x which is currently 5 */
ii) Final methods
Final keywords for methods work similarly as it does for variables. When we
declare or write final methods, we are not allowed to re-use or override that
method in any other class in the code. For ex:
class Dollars {
final void myCurrency() {
System.out.println("100 American cents make 1 US
DOllar");
}
}
class Euros extends Dollars{
void myCurrency() {
System.out.println("0.89 Euros make 1
Dollar"); /*will give a compile time error:
cannot override a final method */
}
}
iii) Final Classes
Final classes once written cannot be inherited into multiple classes, in
simple words final class cannot be extended (or be a parent class to any
subclass) inside the code. For ex:
final class Dollars {
void
myCurrency() {
System.out.println("100 American cents make 1 US
DOllar");
}
}
class Euros extends Dollars{
void myCurrency() {
System.out.println("0.89 Euros make 1
Dollar"); /*will give a compile time error:
the type Euros cannot subclass the final class*/
}
}
Hope you are clear on this topic do read our more articles on JAVA LANGUAGE.
If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".
This article is SUBMITTED By : Pranjal Rai
Do subscribe to our daily blog update by clicking here.
Thank You!
No comments:
Post a Comment