Assuming pencils have only a length attribute and that sharpen reduces the lengt
ID: 3811953 • Letter: A
Question
Assuming pencils have only a length attribute and that sharpen reduces the length of apencil by the given amount, what are the abstract values of qp1 and qp2 at the end ofthe code below? What is the value of ans, if the equals method in Pencil classoverrides and contains a proper equality checking code? What is the value of ans, ifit does not?
public void Example {
IQueue<Pencil> qp1 = new Queue1<>(2);
IQueue<Pencil> qp2 = new Queue1-Override<>(2);
IQueue<Pencil> qp3;
Pencil p1 = new Pencil(20);
Pencil p2 = new Pencil(40);
Pencil p3 = p2;
qp1.enqueue(p1);
qp1.enqueue(p2);
p3.sharpen(20);
if (p1.equals(p3))
qp3 = qp1;
else qp3 = qp2;
int ans = qp3.length();
}
Explanation / Answer
Please find explanation and answer in comment.
public void Example {
IQueue<Pencil> qp1 = new Queue1<>(2);
IQueue<Pencil> qp2 = new Queue1-Override<>(2);
IQueue<Pencil> qp3;
Pencil p1 = new Pencil(20);
Pencil p2 = new Pencil(40);
Pencil p3 = p2; // p3 and p2 pointing to same object
qp1.enqueue(p1); // adding p1 in qp1
qp1.enqueue(p2); // adding p2 in qp1
p3.sharpen(20); // reducing the value of object pointed by p3 nad p2 by 20
if(p1.equals(p3)) // since p1 and p3 has same value equal to 20
qp3 = qp1; // qp3 pointing to same object that qp1 points
else
qp3 = qp2;
int ans = qp3.length(); // since qp3 pinting to qp1 (in if condition)
// Output: 2
}