In Java, the keyword final can be used in various contexts. In all contexts, it prevents the modification or redefinition of the existing entity whether it is a variable, function or a class. Generally final keyword is used for the following purposes.
1. To define constants
2. To prevent overriding of methods
3. To prevent inheritance
2. To prevent overriding of methods
3. To prevent inheritance
final keyword to define constants
If you want to define a constant, you can use the final keyword while declaring a variable and make it a constant.
PI is defined as a constant in the following example.
If you want to define a constant, you can use the final keyword while declaring a variable and make it a constant.
PI is defined as a constant in the following example.
Circle.java
public class Circle {
protected double raduis;
public final double PI = 3.14;
public double getRadius() {
return this.raduis;
}
public void setRadius(double raduis) {
this.raduis = raduis;
}
public double area() {
return PI * (this.raduis * this.raduis) ;
}
public double perimeter(){
return 2 * PI * this.raduis;
}
}
return 2 * PI * this.raduis;
}
}
final keyword to prevent overriding
Suppose you have a base class called Account and it has a member function boolean setOperative(boolean status) to set the account’s status to inoperative or operative. Another class SBAccount inherits the Account class. By default in SBAccount class the function boolean setOperative(boolean status) can be overridden and you can give a new definition for the function. However, here you want to keep the existing definition of the function available in Account class as it is in SBAccount class and in all classes derived from the Account class. That means the definition provided in Account class is the final version and it should not be modified by derived classes. It can be achieved by simply adding the final keyword while defining the function in the Account (base) class.
Account.java
public class Account {
protected String accno;
protected String accholder;
protected boolean isoperative;
public final boolean setOperative(boolean status) {
this.isoperative = status;
}
}
final keyword to prevent inheritance
final keyword is used to prevent a class from being extended. That means if you are defining a class as final, it cannot be extended further. If you want to prevent inheriting from (extending) Circle class, it can be defined as a final class like below:
Circle.java - Defined as final
public final class Circle {
protected double raduis;
public final double PI = 3.14;
public double getRadius() {
return this.raduis;
}
public void setRadius(double raduis) {
this.raduis = raduis;
}
public double area() {
return PI * (this.raduis * this.raduis) ;
}
public double perimeter(){
return 2 * PI * this.raduis;
}
}
No comments:
Post a Comment