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 class B, that has two int attributes and an A attribute, that is another class A. It also has an f() method. 
  • We create a new instance of B class, and call its f() method. Then we change the values of i and j 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button