Search Logic Blocks

Tuesday, October 20, 2020

Java: final keyword

We have already seen usage of the final keyword in the post related to constants. When the final keyword is used with the variables, the variable value can not be changed.
final double pi = 3.14;
In same way, when the final keyword is used with any method, the method becomes final means the method can not be overridden in subclasses.
final int sum(int a, int b) {
return a+b;
}
And if the final keyword is used with a class, that class can not be inherited or subclassed. Abstract class can not be a final class as abstract class as the object of the abstract class can not be instantiated. Here is the final class Square, which can not be subclassed further -
public final class Square extends Shape{
String
fillColor;
// Square Constructor with no arguments
Square() {
super();
this.fillColor = "Blue";
}

// Square Constructor with one argument
Square(String fillColor) {
super();
this.fillColor = fillColor;
}

// Square Constructor with two arguments
Square(double width, String fillColor) {
super(width, width);
this.fillColor = fillColor;
}

// Returns the text telling what shape it is
public String whatShape() {
return "Square";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((width * width) * 100) / 100.0;
}

public void setColor(String color) {
super.setColor(color);
this.fillColor = color;
}

public void setDiffColor(String fillcolor, String bordercolor) {
this.fillColor = fillcolor;
super.setColor(bordercolor);
}
}
So, the final keyword prevents the variables values to be changed, prevents methods from being overridden and also prevents a class from being inherited.

No comments: