- In Java final keyword can be used with variable,function,class.
1) When a variable is declared final we cannot change its value
class CharacterInWord{
final int char_total=45;//final variable
void total(){
char_total=60;
}
public static void main(String args[]){
CharacterInWord charObj=new CharacterInWord();
charObj.run();
}
}
Output: Compile Time Error
2) When a function is declared final we cannot override it’s method
class Vehicle{
final void status(){
System.out.println("running");
}
}
class Bike extends Vehicle{
void status(){
System.out.println("running safely with 70kmph");
}
public static void main(String args[])
{
Bike bike= new Bike ();
bike.status();
}
)
Output:Compile Time Error
3) When a class is declared final we cannot use inheritance(we cannot extend it)
final class Vehicle{
}
class Bike extends Vehicle{
void status(){
System.out.println("running safely with 70kmph");
}
public static void main(String args[]){
Bike bike= new Bike ();
bike.status();
}
}
Output: Compile Time Error
Can we inherit final method ?
- Yes,we can inherit final method but we cannot override it.
class Vehicle{
final void status()
{
System.out.println("vehicle is running");
}
}
class Bike extends Vehicle{
public static void main(String args[])
{
new Bike().status();
}
}
Output:vehicle is running
Blank or Uninitialized final variable
- A final variable not initialized at the time of declaration is known as blank final variable. We can initialize blank final variable only in constructor and once initialized we cannot change value of blank final variable.
class Citizen{
final int nationalID; //blank final variable
Citizen()
{
nationalID=101;
System.out.println(nationalID);
}
public static void main(String args[]){
new Citizen();
}
}
Output: 101
static blank final variable
- A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
class Student{
static final int rollnumber;//static blank final variable
static{
rollnumber=45;
}
public static void main(String args[]){
System.out.println(Student.rollnumber);
}
}
Output:45
final parameter
- If we declare any parameter as final, we cannot change its value.
class Vehicle{
int speed(final int n){
n=n+10;//can't be changed as n is final
return n*n;
}
public static void main(String args[]){
Vehicle vehicle=new Vehicle();
System.out.println(vehicle.speed(45));
}
}
Output:Compile Time Error
Q) Can we declare a constructor final?
- No, because constructor is never inherited.