Java final classes and methods

In Java it is possible to prevent a class to be extended by declaring it final. The key final is used for classes that are complete and that is in contrast to abstract classes which are incomplete and they only can be used as superclasses.

 

What is a final class in Java?

Final classes are classes that can not be extended or they can never be superclasses.

General information and rules that apply to a final class.

  1. A final class can not be extended that is in contrast to abstract classes which can only be extended.
  2. A final class is a complete class unlike abstract classes which are incomplete.
  3. The methods of a final class cannot be overridden.
  4. A final class cannot be abstract, because it is complete.
  5. Final classes can extend other classes.
  6. Making a class final enforces that the class become immutable such as the String class.
  7. You can prevent a final class to be instantiated by declaring its constructor private.
  8. Yo can make all the members of a final class static.

final-classes-color

The Java API includes many final classes such as the String class, Math and the System class.

 

What is a final method?

A final method in Java is a complete method that cannot be overridden.

General information and rules that apply to a final method

1- A final method cannot be overridden.

2- A final method is complete.

 

There is a logic behind the concept of final methods. Why would any programmer override a complete method? An example that makes overriding a method unnecessary is a method that returns the largest number of two numbers. See the exercise below for details.

 

What is a final variable?

The value of a final variable cannot be changed once it has been initialized. We can actually call a final variable a constant.

General information and rules that apply to a final variable

1- A final variable is a constant and cannot be changed during running the program.

2- All the variables defined in an interface are implicitly final.

3- A final variable does not need to be initialized at its declaration, but you must initialize them before using them.

 

Why declaring a class or a method final?

In some cases extending a class and overriding its methods makes no sense. In the example of the class Programmer that extends Employee, we have overridden the method printData as follows:

 

public class Employee {

	String name;
	int age;
	double salary;

	public void printData(){
		System.out.println("name: " + name);
		System.out.println("age: " + age);
		System.out.println("salary: " + salary);
	}
}

 

In the class Programmer we have overridden the method printData to print the name, age, salary, while we added the language to the method to determine which programming language the programmer uses.

 

public class Programmer extends Employee {

	String language;

	public void printData(){
		super.printData();
		System.out.println("language: " + language);
	}
}

 

In the above case, it is not a good idea to declare the class Employee final, because by extending the class we can create special types of employees such as programmers and database professionals Read More: Java Inheritance. . There are many Java classes that are declared final such as the class String, Math and System, but we use for simplicity the following example.

 

Example:

In the following example we have a class Calculation which contains two methods namely getGreater and getSquare. Why would any programmer extend a class like that? Both two methods are complete. getGreater returns the greater number of two numbers and getSquare returns the square number of an integer. Defining such a class final prevents anyone to extend it.

 

You might even consider declaring both methods static, because it is not necessary to create objects to use those methods. We create unlimited objects of the class Employee, because an employee could be Jack, Ben, Frank and any other employees. No matter how many objects you create, the methods getGreater and getSquare calculate the same result.

When the following code compiled and run, it will write the following to the standard output.

78.0
100.0

 

public final class Calculation {

	public static double getGreater(double d1, double d2){
		if(d1 > d2) {
			return d1;
		}
		else if(d1 < d2) {
			return d2;
		}
		else {
			return - 1; // the two numbers are equal
		}
	}
	public static double getSquare(double d){
		return d * d;
	}
}

public class TestCalculation {

	public static void main(String[] args){
		Calculation c = new Calculation();
		System.out.println(c.getGreater(59,78));
		System.out.println(c.getSquare(10));
	}
}

Exercise

  1. In the above code, how would you prevent creating objects of the calculation class?
  2. If you prevent instantiating the class, then how can you access the two methods getGreater and getSquare?

Solution

  1. By declaring a private constructor of the class Calculation, you can prevent instantiating it.
  2. When you prevent instantiating a class, you can access the static variables and methods by using the name of the class as shown below.

 

public final class Calculation {

	private Calculation() {
	}
	public static double getGreater(double d1, double d2){
		if(d1 > d2) {
			return d1;
		}
		else if(d1 < d2) {
			return d2;
		}
		else {
			return - 1; // the two numbers are equal
		}
	}
	public static double getSquare(double d){
		return d * d;
	}
}

public class TestCalculation {

	public static void main(String[] args){
		System.out.println(Calculation.getGreater(29,29));
		System.out.println(Calculation.getGreater(159,160));
		System.out.println(Calculation.getSquare(8));
	}
}

 

This code writes the following to the standard output.

-1.0
160.0
64.0


Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked for several big as well as small companies and later as a freelancer.
He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

1 Comment

Add a Comment
  1. You’re on top of the game. Thanks for shraing.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017