69.3k views
0 votes
Assume the class Circle has an accessor called getRadius() and a mutator called setRadius(). What is the output of the following code?

Circle c1 = new Circle(3);

Circle c2 = c1;

c1.setRadius(4);

System.out.println(c2.getRadius());

c.What is the output of the following code:

Circle c1 = new Circle(3);

Circle c2 = new Circle(3);

c1.setRadius(4);

System.out.println(c2.getRadius());
a) 4
b) 3
c) 6
d) 8

User AggieEric
by
7.6k points

1 Answer

6 votes

The output of the first code segment is 4, as c2 is a reference to the same object as c1, which had its radius set to 4. The output of the second code segment is 3 since c2 is a separate object from c1 and retains its original radius.

The code segments you provided deal with the basics of object-oriented programming in Java, specifically with how objects are assigned and modified.

For the first code segment:

Circle c1 = new Circle(3);
Circle c2 = c1;
c1.setRadius(4);
System.out.println(c2.getRadius());

Since c2 is a reference to the same object as c1, any changes to c1 will also reflect in c2. Therefore, when c1.setRadius(4) is called, the radius of the circle referenced by c2 is also 4. Hence, the output will be 4.

For the second code segment:

Circle c1 = new Circle(3);
Circle c2 = new Circle(3);
c1.setRadius(4);
System.out.println(c2.getRadius());

In this case, c2 is a reference to a new Circle object, independent of c1. Therefore, changes made to the radius of c1 do not affect c2. As a result, the output will be the original radius of c2, which is 3.

The correct answer to the student's second question is therefore (b) 3.

User AnchovyLegend
by
8.4k points