Final non-access modifier

0

In the last article, I have shown you examples of member access modifiers. In this article, I will introduce you to non-access modifiers final and abstract.

Non-Access Modifier – final

You can add final to a class declaration, class member or a member field. We will see how final modifies the behavior at each level.

Final Class

When we declare a class with final keyword, it means that the class behavior is final and we won’t be able to¬†extend it further.

package javarticles.finalmodifier;

final class A {
    void doSomething() {
    }
}

If we try to extend class A, compiler issues error.

package javarticles.finalmodifier;

public class B extends A {
}

The type B cannot subclass the final class A

We can get the same behavior without using final keyword. For example, in the below class declaration, I made the constructor private:

package javarticles.finalmodifier;

public class C {
    private C() {
    }
}

Since C's constructor is private, we will never be able to extend it. If we try to extend it, compiler issues error:
Implicit super constructor C() is not visible for default constructor. Must define an explicit constructor

package javarticles.finalmodifier;
public class D extends C {
}

Final Methods

final can be added at method level too. If a method is final, it means it can’t be overridden anymore.

Why do we need to make a class final and prohibit inheritance?

There are certain objects which we would like to be immutable and there are others which we would like to be extended. Class String is one of the core Java classes which is immutable. One of the main condition for a class to be immutable is that we shouldn’t provide any method that modifies the state of the object.
Another important point is to make sure that the methods may not be overridden. Instead of making sure each method is final we can make the class itself final.

For example, class E below has a final method doSomethng():

package javarticles.finalmodifier;

public class E {
    public final void doSomething() {       
    }
}

If we try to override it in F, compiler will issue an error.

package javarticles.finalmodifier;

public class F extends E {
    public void doSomething() {
    }
}

Cannot override the final method from E

Share.

Leave A Reply