class
Final class example
With this example we are going to demonstrate how to use a final
class. In short, to use a final class we have followed the steps below:
- We have created a
final
classB
, that has twoint
attributes and anA
attribute, that is another classA
. It also has anf()
method. - We create a new instance of
B
class, and call itsf()
method. Then we change the values ofi
andj
attributes. - The values of the final class can change, but if we try to extend the final class from another one, an error will occur, because classes cannot subclass a final class.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; //remove the comment and see what happens class A { //extends B{ } //! class Further extends B {} // error: Cannot extend final class 'B' final class B{ int i = 7; int j = 1; A x = new A(); void f() { System.out.println("B.f() function...."); } } public class FinalClass { public static void main(String[] args) { B n = new B(); n.f(); n.i = 40; n.j++; System.out.println("n.i = "+n.i+", n.j = "+n.j); } }
Output:
B.f() function....
n.i = 40, n.j = 2
This was an example of how to use a final class in Java.