שאלה ב-JAVA

_alon_

New member
שאלה ב-JAVA

שאלה ב-JAVA, העברת פרמטרים בפונקציות. פרמטרים עוברים כ-refrence, ולכן אם אשנה את האוביקט בתוך הפונקציה גם מחוצה לה הוא ישתנה. למה בתוכנית הבאה זה לא כך? public class X { public static void main(String[] args) { X myX = new X(); Y myY = null; myX.f(myY); if (myY == null) System.out.println("myY is null here. why???"); // ^^^ why did i get here? passing by refrence means that if the function changed the object it´s changed here also, right? ^^^^ } // end of main func public void f(Y myY) { myY = new Y(); // myY is no longer null. } } // end of class X
 

_alon_

New member
lets try again but this time in eng

can anyone tell me why, if parameters pass as refrence, do myY turns back to null, after returning from function f thanks, alon
public class X { public static void main(String[] args) { X myX = new X(); Y myY = null; myX.f(myY); if (myY == null) System.out.println("myY is null here. why???"); // ^^^ why did i get here? passing by refrence means that if the function changed the object it´s changed here also, right? ^^^^ } // end of main func public void f(Y myY) { myY = new Y(); // myY is no longer null. } } // end of class X​
 

albanetc

New member
wrong!

you don´t pass object by reference, what you pass is a handle and you pass it by value. in your example you can do f(null) as well, just don´t expect that after this call ´null´ would point to anything. here´s what´s going on: Y myY = null; // a new handle is created on stack. myX.f (myY); // here the handle (null) is copied and placed on stack. // in myX.f (Y myY): new handle myY is created and initialised // by what is on the stack (null). { myY = new Y(); // new Y object is created. local copy of handle myY is initialized // by its address. } // local myY got out of scope, it is cleaned from stack. // Y object created in function has no handle that points to it. // it will be garbage-collected sometime. if () etc... // myY in main stayed null. take a look at bruce eckel´s thinking in java, chapter 12
 
למעלה