final is a keyword which is used in variable, method and
class.
Wednesday, 24 January 2018
final Keyword In Java
final variable
If a variable is declared as final
then we cannot change the value, once it is initialized.
In other words the variable is
constant
Example:
class DemoFinal{
final int x=50; //final variable
void display()
{
x=78;
System.out.println("x is:"+x);
}
public static void main(String args[]){
DemoFinal df=new
DemoFinal();
df.display();
}
}
Output: Compile time error
Note:
It provides compile time error because
x is declared as final and the value is 50, again you assign the value of x is 78.So
it’s not possible because x is final variable and it acts like a constant .once
you assign the value, you cannot change it.
If a method is declared as final then
we cannot write the same method again and again.
In other words final method cannot be
overridden.
Note:
final method can be overloaded because
you know that overloading is same name and different parameter.
Example:
class DemoFinal{
final void display(int x){
System.out.println("square is:"+(x*x));
}
}
class Result extends DemoFinal
{
void display(int x){
System.out.println("cube is:"+(x*x*x));
}
public static void main(String args[]){
Result r1=new Result();
r1.display(7);
}
}
Output:
Compile time error
Note:
It provides compile time error because display method is declared as final
and again you repeat same method in child
class and you know that final method cannot be overridden
final class
If a class is declared as final then
we cannot extends new class from final class.
In other words final class cannot be
inherited.
Example:
final class DemoFinal{
void display(int x){
System.out.println("square is:"+(x*x));
}
}
class Result extends DemoFinal
{
void display(int x){
super.display(5)
System.out.println("cube is:"+(x*x*x));
}
public static void main(String args[]){
Result r1=new Result();
r1.display(6);
}
}
Output:
Compile time error
It provides compile time error because DemoFinal class is declared as final and you know that final
class cannot be inherited.
Subscribe to:
Post Comments (Atom)
apply function in R
1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...
-
a)Structural diagrams Structure diagrams depict the static structure of the elements in your system.It shows the things in the system - ...
-
index.html <html> <head><title>Sum of two numbers</title></head> <body> <form method="pos...
-
Write a program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer, calculate percentage and grade acc...
No comments:
Post a Comment