ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Base implements Cloneable {
int x = 5;
@Override
public Base clone() throws CloneNotSupportedException {
return (Base) super.clone();
}
}
// in main:
Base b1 = new Base();
Base b2 = b1.clone();
b2.x = 99;
System.out.println(b1.x + " " + b2.x + " " + (b1 == b2));- A. 5 99 false
- B. 99 99 true
- C. 5 5 false
- D. 5 99 true
Correct answer: A. 5 99 false
Object.clone() performs a shallow field-by-field copy into a NEW object, so b2 is a distinct object (b1 == b2 is false) starting with the same x=5; mutating b2.x to 99 only affects b2's own copy, leaving b1.x at 5.
More OOP with C++ and Java questions
- What is printed? java class Node<T extends Comparable<T>> { T value; Node(T v) { value = v; } boolean isGreaterThan(Node<T> other) {…
- What is printed? cpp struct Base { virtual void greet() const { cout << "Base "; } }; struct Derived : Base { void greet() const override…
- What is printed? cpp class Base { public: Base(const Base&) = delete; Base() = default; virtual void show() { cout << "Base"; } }; class…
- What is printed? java class Vehicle { void move() { System.out.print("Vehicle moves "); } } class Car extends Vehicle { @Override void…
- What is printed? java class Animal { String category() { return "Animal"; } } class Mammal extends Animal { @Override String category() {…
- What is printed? java class Shape { double area() { return 0; } @Override public String toString() { return getClass().getSimpleName() +…