ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
interface Repository<T> {
void save(T item);
T find(int id);
}
class UserRepository implements Repository<String> {
Map<Integer, String> store = new HashMap<>();
public void save(String item) { store.put(store.size(), item); }
public String find(int id) { return store.get(id); }
}
// in main:
Repository<String> repo = new UserRepository();
repo.save("alice");
repo.save("bob");
System.out.println(repo.find(1));- A. bob
- B. alice
- C. null
- D. Compilation error: Repository<String> cannot hold a UserRepository
Correct answer: A. bob
save("alice") stores at key 0 (store.size() was 0 at that point); save("bob") stores at key 1 (store.size() was then 1); find(1) retrieves the value at key 1, "bob".
More OOP with C++ and Java questions
- What is printed? cpp class Printable { public: virtual void print() const = 0; virtual ~Printable() = default; }; class Report : public…
- What is printed? java class Shape implements Comparable<Shape> { double area; Shape(double a) { area = a; } public int compareTo(Shape o)…
- What is printed? java class Base { public Object process() { return "base-result"; } } class Derived extends Base { @Override public…
- What is printed? cpp class Logger { public: static Logger& instance() { static Logger inst; return inst; } void log(const string& msg) {…
- What is printed? java class EventBus { private static EventBus instance; private EventBus() { System.out.print("created "); } public…
- What is printed? java class Base { Base clone2() { return new Base(); } } class Derived extends Base { @Override Derived clone2() { return…