| Start |
|---|
| Object References as method parameters This topic explains the concept of an object reference; it is targeted at people who are new to programming in Java. You should already be familiar with some terms and meanings: class definition, main method, object instance, and the calling of methods "on" an object, and passing parameters to methods. To be fully competent in Java programming, you should be able to explain this example to someone else off the top of your head. Its concepts are fundamental to understanding how Java works. As you can see, we have a The method called sets the So what would get printed? So why does the change made to When the call is made, the main method passes an object reference for Another way of saying the same thing: Contrast this with the integer that is passed. Since this is a primitive (opens new window) int (and not an Integer object instance), it is passed "by value", meaning its value is provided to the method, not a pointer to the original integer passed in. The method can change it for the method's own purposes, but that does not affect the variable used when the method call is made. In Java, all primitives are passed by value. Objects are passed by reference, which means that a pointer to the object is passed as the parameter to any methods that take them. One less-obvious thing this means: it is not possible for a called method to create a new object and return it as one of the parameters. The only way for a method to return an object that is created, directly or indirectly, by the method call, is as a return value from the method. Let's first see how that would not work, and then how it would work. Let's add another method to our little example here: And, back in the Now the program would print out: What happened to the object that had George? Well, the parameter that was passed in was a pointer to Linda; when the If that is what the writer wanted to do, he would need to return the newly created object from the method, something like this: Then call it like this: And the entire program output would now be: Here is the entire program, with both additions: RemarksThis should help you understand a "Null Pointer Exception" -- one gets one of those because an object reference is null, but the program code expects the program to use something in that object reference. However, that deserves its own topic... |
Read Article
https://develop.horje.com/learn/1434/reference