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

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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?

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}