Call by value

0001001

Bekanntes Mitglied
Folgendes Beispiel:
Java:
import java.awt.Point;


public class Test {

  public static void main(String[] args) {
	Point p = new Point(10,10);	
	Point modifiedPoint = modify(p);
	
	System.out.println(p);                   //Ergebnis: x=20,y=20
	System.out.println(modifiedPoint); //Ergebnis: x=20,y=20
  }
  
  public static Point modify(Point p){
	  Point q = p;
	  q.x=20;
	  q.y=20;
	  return q;
  }
}

Wie man sieht, sind beide Punkte nach Aufruf der modify Methode x=20,y=20, also auch der Point p.
Gibts ne Möglichlichkeit, das anders zu machen? So dass der Point p nicht verändert wird?
 
ja, zeile 15 : Point q = new Point(p); statt Point q =p;

sonst hast du mit q keine kopie sondern nur eine zweite referenz auf p
 
Java:
	Point q = new Point(p.x, p.y);
//oder
//	Point q = (Point) p.clone();
//oder
//	Point q = new Point(p);
 

Zurück
Oben