Over a million developers have joined DZone.

Should I make a class final?

DZone's Guide to

Should I make a class final?

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

One question comes out of my mind for several times recently. Should I make a class final if I know there’s no use case to inherit it? I think it’s a good practice to mark a class final if you want the class behavior immutable to some extent. But this view holds true until the popularity of AOP.

Speaking of Spring AOP, it’s based on running time proxy-based model. If the original class implements any Interface(s), Spring creates a proxy implementing same interface(s) wrapping the original class and weaves advices (typical decoration pattern). But for the case that original class doesn’t implement any interface(s), Spring creates a proxy inheriting it and weaves advices. Then you will see exception indicating ‘can’t extends final class’.

That’s where my question comes from. With AOP, does the practice marking a class final to be immutable become obsolete?

I didn’t use AspectJ properly so far, but I know it supports compile time weaving and load time weaving besides run time weaving. Also it supports more pointcut ways. Does my question apply to AspectJ or not, I am not quite sure. I think it really depends on how the special compiler and classloader weaves advices.

Any thoughts on this?

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}