b.equals(c) 4. Here is a simple Point and Circle class. class Point ( private do
ID: 3600469 • Letter: B
Question
b.equals(c) 4. Here is a simple Point and Circle class. class Point ( private double x, y; class Circle private Point c; /1 center private double r; // radius public Point (double x, double y) f this.x x; public Circle(Point c, double r) { this . r=r; this . y = y; this. c = c ; public double getX0f return x; > public double getYOf return y; h // more stuff (a) The constructor in Circle has a "privacy leak". Explain why. Hint: Consider the following code. Point p = new Point (1,2); Circle c= new Circle (p, 10); p.setX (100); (b) Rewrite the Circle constructor to fix this problem.Explanation / Answer
In Java, assignment operator works differently for composite type (classes) from simple types (int,float...etc).
For composite types, the reference of the object will copied rather than the value.
So here in Circle class constructor when this.c = c; is used we are copying the reference of the point c to the point c of circle class. So when the point c is changed then the point c in circle class will also get changed.
Lets take an example using the hint provided.
Point p = new Point(1, 2); // a new point p has been created
Circle c = new Circle(p, 10); // we are passing point p to circle class, as per existing design we are copying the reference of point p to the point c in circle class rather than values of p (1,2).
System.out.println(c.getP().getX()); // this will print 1 which is good
p.setX(100); // Now change x of point p to 100
System.out.println(c.getP().getX()); // this will print 100 insted of 1, which mean out circle class has been changed internall when we assgin a new value to point class, which should not happen.
Now lets rewrite constructor of circle class so that privacy leak can be mitigated.
public Circle(Point p, double r) {
Point p1 = new Point(p.getX(), p.getY()); // here we are creating a new point object p1 using the data provided by point p
this.p = p1; // and assiging the p1 to the circle class insted of p
this.r = r;
}
Now the output of below would be
Point p = new Point(1, 2);
Circle c = new Circle(p, 10);
System.out.println(c.getP().getX()); // this will print 1
p.setX(100);
System.out.println(c.getP().getX()); // this will print 1
so here circle class object not affected when we change point class object.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.