OOPS in JAVA 15
final Keyword
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
1. variable
2. method
3. class
1. Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable.
class Vehicle{
final int speedlimit=100;//final variable
void run(){
speedlimit=360;
}
public static void main(String args[]){
Vehicle obj=new Vehicle();
obj.run();
}
} //end of class
Output: Compile Time Error
Output: Compile Time Error
2. Java final method
If you make any method as final, you cannot override it.
Example.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
3. Java final class
If you make any class as final, you cannot extend it.
Example.
final class Vehicle{
}
class Bike extends Vehicle{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Bike bike= new Bike();
bike.run();
}
}
Q. Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it.
Q. What is blank or uninitialized final variable?
Ans) A final variable that is not initialized at the time of declaration is known as blank final variable.
It can be initialized only in constructor.
Q. What is blank or uninitialized final variable?
Ans) If you declare any parameter as final, you cannot change the value of it.
Q. Can we declare a constructor final?
Ans) No, because constructor is never inherited.
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )