ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
// in main:
Calculator calc = new Calculator();
System.out.println(calc.add(1, 2) + " " + calc.add(1.0, 2) + " " + calc.add(1, 2, 3));- A. 3 3.0 6
- B. 3 3 6
- C. Compilation error: ambiguous overload add(1.0, 2)
- D. 3.0 3.0 6
Correct answer: A. 3 3.0 6
These are all distinct overloads by parameter count/type (not overriding, since there's no inheritance involved): add(1,2) matches add(int,int) exactly (3); add(1.0, 2) requires widening 2 to double, uniquely matching add(double,double) (3.0); add(1,2,3) matches the three-arg overload (6).
More OOP with C++ and Java questions
- What is printed? java class Shape { void draw() { System.out.println("Shape.draw"); } } class Circle extends Shape { void draw() {…
- Does this compile? java class Base { void greet() { System.out.println("Base.greet"); } } class Derived extends Base { @Override void…
- What is printed? java class Repo<T> { private List<T> items = new ArrayList<>(); void add(T item) { items.add(item); } T get(int i) {…
- What is printed? java interface Shape { double area(); default String describe() { return "Shape with area " + area(); } } class Square…
- What is printed? cpp struct A { int x = 10; virtual int getX() { return x; } }; struct B : A { int x = 20; int getX() override { return x…
- What is printed? java class Util { static int counter = 0; static void inc() { counter++; } } class UtilChild extends Util { } public…