Can someone explain to me what the reasoning behind passing by “value” and not by “reference” in Java is?

后端 未结 15 1518
[愿得一人]
[愿得一人] 2020-12-31 17:24

I\'m fairly new to Java (been writing other stuff for many years) and unless I\'m missing something (and I\'m happy to be wrong here) the following is a fatal flaw...

<
15条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 18:12

    Since my original answer was "Why it happened" and not "Why was the language designed so it happened," I'll give this another go.

    To simplify things, I'll get rid of the method call and show what is happening in another way.

    String a = "hello";
    String b = a;
    String b = "howdy"
    
    System.out.print(a) //prints hello
    

    To get the last statement to print "hello", b has to point to the same "hole" in memory that a points to (a pointer). This is what you want when you want pass by reference. There are a couple of reasons Java decided not to go this direction:

    • Pointers are Confusing The designers of Java tried to remove some of the more confusing things about other languages. Pointers are one of the most misunderstood and improperly used constructs of C/C++ along with operator overloading.

    • Pointers are Security Risks Pointers cause many security problems when misused. A malicious program assigns something to that part of memory, then what you thought was your object is actually someone else's. (Java already got rid of the biggest security problem, buffer overflows, with checked arrays)

    • Abstraction Leakage When you start dealing with "What's in memory and where" exactly, your abstraction becomes less of an abstraction. While abstraction leakage almost certainly creeps into a language, the designers didn't want to bake it in directly.

    • Objects Are All You Care About In Java, everything is an object, not the space an object occupies. Adding pointers would make the space an object occupies importantant, though.......

    You could emulate what you want by creating a "Hole" object. You could even use generics to make it type safe. For example:

    public class Hole {
       private T objectInHole;
    
       public void putInHole(T object) {
          this.objectInHole = object;
       }
       public T getOutOfHole() {
          return objectInHole;
       }
    
       public String toString() {
          return objectInHole.toString();
       }
       .....equals, hashCode, etc.
    }
    
    
    Hole foo = new Hole foo){
       foo.putInHole("howdy");
    }
    

提交回复
热议问题