Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

java - Why declare a function argument to be final?

I'm currently working my way through the book "Teach Yourself Android Application Development in 24 Hours" published by Sams. I'm relatively new to Java, Android or otherwise. I have a very solid background in ActionScript 3, which has enough similarities with Java that the language itself isn't hard to grasp, but I do still have some questions about the rationale behind some of the code samples in the book. For example, here's a function that comes with the sample code for Hour 9:

private void processScores(final TableLayout scoreTable, 
      XmlResourceParser scores) throws IOException, XmlPullParserException{

In this function signature, the authors have declared the scoreTable argument as final. I'm a little puzzled as to why they did this. It wouldn't cross my mind to even attempt to assign a new value to the function argument scoreTable (it's considered a bad practice in ActionScript). Further, I haven't actually seen anyone do this in any of the real-world Java I've examined or ported into AS3.

Is there something specific about Android development that makes it a necessity to sometimes declare certain function arguments as final?

Why is the TableLayout object declared final, but not the XmlResourceParser?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two main reasons you might want to mark an argument final. First, if you're planning on using the argument in an anonymous inner class, then you must mark it final so that it can be referenced in that class. This is actually a pretty common use case for marking arguments final.

The other common reason to mark arguments final is to prevent yourself from accidentally overwriting them. If you really don't want to change the arguments, then perhaps you should mark them final so that if you actually do, you'll get the error at compile-time rather than finding out at runtime that your code has a bug.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...