Java
In this tutorial we will learn about final class in Java programming language.
In the previous tutorials we learned about final variables and final methods.
So, we know that if we want to create a constant then we can declare a final variable. And if we want to prevent method overriding then we can define a final method.
Now, lets talk about the final class.
final
If we want to prevent a class from getting inherited then we set the class as final.
final class MyClass { // some code goes here... }
Where, MyClass is the name of the class and it can't be inherited as we are using the final keyword.
MyClass
Note! If a class is declared as final then all its methods implicitly gets declared as final.
We can still instantiate an object of the final class.
In the following example we are declaring the Hello class as final.
Hello
// this class can't be inherited // as we are using final final class Hello { void greetings() { System.out.println("Hello World"); } } // inheriting Hello class is not allowed /** * class Awesome extends Hello { * // some code goes here... * } */ // main class public class Example { public static void main(String[] args) { // create an object Hello obj = new Hello(); // calling method obj.greetings(); } }
Output:
$ javac Example.java $ java Example Hello World
If we try to inherit the Hello class then we will get the following error.
$ javac Example.java Example.java:10: error: cannot inherit from final Hello class Awesome extends Hello { ^ 1 error
In the following example we have a final class Box that can't be inherited.
Box
We also have the GiftBox class that uses the method of the Box class.
GiftBox
We are passing the object of the Box class to the GiftBox class to take help of its getVolume() method.
getVolume()
Check the passing objects as arguments to methods tutorial for more info.
// this class is declared as final // so it can't be inherited final class Box { public double getVolume(double length, double width, double height) { return length * width * height; } } class GiftBox { // member variables private double length; private double width; private double height; // constructor with parameters GiftBox(double length, double width, double height) { // initialising the variables this.length = length; this.width = width; this.height = height; } // this method takes Box object as argument // and using the Box getVolume method // it prints the volume of the GiftBox public void printVolume(Box bObj) { double volume = bObj.getVolume(this.length, this.width, this.height); System.out.println("Volume of the GiftBox: " + volume); } } // main class public class Example { public static void main(String[] args) { // instantiate object Box bObj = new Box(); GiftBox obj = new GiftBox(5, 4, 3); // output obj.printVolume(bObj); } }
$ javac Example.java $ java Example Volume of the GiftBox: 60.0