页面

2011-01-25

关于java函数参数传递的精辟论述

原文在这里:
http://www.yoda.arachsys.com/java/passing.html
下面是节选:
Parameter passing in Java - by reference or by value?

This is another common question on Java newsgroups, made worse by the fact that people who should know better still perpetuate the following myth: Myth: "Objects are passed by reference; primitives are passed by value."

Some proponents of this then say:"Ah, except for immutable objects which are passed by value ..." which introduces loads of rules without really tackling how Java works. Fortunately the truth is much simpler:
Truth #1: Everything in Java is passed by value. Objects, however, are never passed at all.

That needs some explanation - after all, if we can't pass objects, how can we do any work? The answer is that we pass references to objects. That sounds like it's getting dangerously close to the myth, until you look at truth #2:
Truth #2: The values of variables are always primitives or references, never objects.

This is probably the single most important point in learning Java properly. It's amazing how far you can actually get without knowing it, in fact - but vast numbers of things suddenly make sense when you grasp it.

没有评论: