Reasoning for making a method final

2019-04-23 13:09发布

Sorry, quick question here, just found something in my notes I don't understand in relation to making a method final. My notes claim you should make a method final for this reason :

Makes it impossible to enforce invariants.

A String should behave as a String.

I don't really understand what is meant by this. Can someone please break it down for me ? Thanks a lot.

8条回答
女痞
2楼-- · 2019-04-23 14:11

There are typically two reasons to make a method final, performance and design. When a method is final, it may be inlined. Before HotSpot compiling (JDK 1.1.x), these methods were usually inlined at compile time, whereas with HotSpot they are inlined at runtime, unless the compiler can guarantee that the inlined method will always be compiled together with the code that uses it. There are two reasons I know for making a local variable or a parameter final. The first reason is that you don't want your code changing the local variable or parameter. It is considered by many to be bad style to change a parameter inside a method as it makes the code unclear. As a habit, some programmers make all their parameters "final" to prevent themselves from changing them. I don't do that, since I find it makes my method signature a bit ugly.

The second reason comes in when we want to access a local variable or parameter from within an inner class. This is the actual reason, as far as I know, that final local variables and parameters were introduced into the Java language in JDK 1.1. Source

查看更多
做个烂人
3楼-- · 2019-04-23 14:12

Yeah basically making anything final means you cannot change it. By this same reasoning, one would make a method final within a class to make it impossible for other subclasses to override this method's functionality. This is applicable to situations where you would absolutely want this one function to always to do this one thing.

查看更多
登录 后发表回答