Yaozong has posted 2 posts at DZone. View Full User Profile

Should I make a class final?

11.21.2012
| 443 views |
  • submit to reddit

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?

Published at DZone with permission of its author, Yaozong Zhu.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: