Java Final Class

Java Final Class

What is the point of final class in Java?

A final class is simply a class that can't be extended. As a result following code will not compile.

final class Owls{

}
class TechyOwls extends Owl{

}

A final class does not mean:

  • All references to this class would act as if they were declared as final
  • All fields in the class are automatically final.

So when is this useful?


public class Car {
    public void move() {
        System.out.println("Moving on road");
    }
}

public class Aeroplane extends Car {

    public void move() {
        System.out.println("Moving in air");
    }
}

This code will compile just fine. But it doesn't make any sense.

An Aeroplane must not extend a Car. There are many specific use cases where a class is designed not to be inherited and final keyword before class prohibits inheritance.

Joshua Bloch's in his Effective Java book said:

Design and document for inheritance or else prohibit it

The interaction of inherited classes with their parent can be unpredictable if the parent wasn't designed to be inherited from.

Classes should be therefore come in two kinds:

  1. classes designed to be extended, and with enough documentation to describe how it should be done.

  2. classes marked final.

Notes:

  • If you are writing purely internal code this may be a bit of overkill. However the extra effort involved in adding five characters to a class file is very small and a future developer can always remove the final.

  • This is a way of hinting that this class was not designed with inheritance in mind.

  • One of the principles of Effective Java is to favor composition over inheritance. The use of the final keyword also helps to enforce that principle.

Conclusion:

Today we looked at sometimes overlooked but yet an useful use of final class. See you in next post. Thanks for reading.

Avatar
Moshiour Rahman
Software Architect

My interests include enterprise software development, robotics, mobile computing and programmable matter.

comments powered by Disqus
Next
Previous

Related