Monday, November 11, 2013

final class, variable, and method

Java does allow you to extend a class, change the value of a variable, and override a method of a class. Sometimes, however, you can modify this behavior to disable extendibility, prevent value of the variable from being changed, and prevent the method from being overridden by using the final keyword.

When the final keyword is written before the name of a class, the class will become a final class. You cannot create a sub-class to extend the final class. You will get a compile error if you try to extend the final class. By placing the final keyword before the name of a variable, the variable will be a constant variable. You can assign a value to the constant variable only one time when it is defined. Further change to the value of the variable will also generate compile error. When the final keyword stays before the name of a method, the method will become a final method. The final method does not allow any code to override it.

In the example code below, the Reader class is a final class. The value of the path variable cannot be further changed by any code in the class. The readText method can be called from other classes. However, it cannot be overridden by any code outside the class.

import java.io.BufferedReader;
import java.io.FileReader;

final class Reader{ //final class
private final String path="d:/test.txt"; //constant variable

public final void readText(){ //final method
try {
FileReader fr=new FileReader(path);
BufferedReader br=new BufferedReader(fr);
String content="";
while((content=br.readLine())!=null){
System.out.println(content);
}
br.close();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}

If you try to extend the Reader by creating another class and use the extends keyword, the compile error will display as shown in the picture below.

final keyword

No comments:

Post a Comment