Avatar of krakatoa
krakatoa
Flag for United Kingdom of Great Britain and Northern Ireland

asked on 

Any clarifying explanations please ?

I've got a reasonable knowledge of Java, but this quote from Java in a Nutshell 6th Ed., seems a bit unsettling for some reason to me :

The following code shows that even after a call to manipulate(), the value contained in variable c is unaltered - it is still holding a reference to
a Circle object of radius 2. If Java was [sic] a pass-by-reference language, it would instead be holding a reference to a radius 3 Circle:

   
public void manipulate(Circle circle){
    
        circle = new Circle(3);
        
    }
    
    Circle c = new Circle(2);
    manipulate(c);
    System.out.println("Radius: "+ c.getRadius());

Open in new window


 . . . when contextualised thusly :

class RefDemo {

Circle c;

    public int /*void*/ manipulate(Circle circle){
    
        circle = new Circle(3);
        return circle.getRadius();
        
    }

    
    public RefDemo(){this.c = new Circle(2);}
    
    public static void main(String[] args){
  
        RefDemo rd = new RefDemo();
        
        System.out.println("Radius:"+(rd.manipulate((rd.c))));
        System.out.println("Radius: "+ rd.c.getRadius());

    }
  
  
  public class Circle {
  
  private int radius;
  
    public Circle(int r){
    
        this.radius = r;
    
    }
    
    public int getRadius(){return this.radius;}
  
  }
  
}

Open in new window

Java

Avatar of undefined
Last Comment
krakatoa

8/22/2022 - Mon