Over a million developers have joined DZone.

Should I make a class final?

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

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?

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}