What does the following print?
1: class SmartCar extends Car { 2: private String getType() { return "smart watch"; } 3: public String getName() { 4: return getType() + ","; 5: } //from w ww . j a v a 2s .c o m 6: } 7: public class Car { 8: private String getType() { return "watch"; } 9: public String getName(String suffix) { 10: return getType() + suffix; 11: } 12: public static void main(String[] args) { 13: Car watch = new Car(); 14: Car smartCar = new SmartCar(); 15: System.out.print(watch.getName(",")); 16: System.out.print(smartCar.getName("")); 17: } 18: }
D.
Line 15 calls the method on line 9 since it is a Car object.
Line 16 is a SmartCar
object.
However, the getName()
method is not overridden in SmartCar
since the method signature is different.
Therefore, the method on line 9 gets called again.
That method calls getType()
.
Since this is a private method, it is not overridden and watch is printed twice.
Option D is correct.