What is the result?

Given:

class Pizza {
java.util.ArrayList toppings;

public final void addTopping(String topping) {
toppings.add(topping);
}
public void removeTopping(String topping) {
toppings.remove(topping);
}
}

public class PepperoniPizza extends Pizza {
public void addTopping(String topping) {
System.out.println(“Cannot add Toppings”);
}

public static void main(String[] args) {
Pizza pizza = new PepperoniPizza();
pizza.addTopping(“Mushrooms”);
pizza.removeTopping(“Peperoni”);
}
}

What is the result?

Given:

class Pizza {
java.util.ArrayList toppings;

public final void addTopping(String topping) {
toppings.add(topping);
}
public void removeTopping(String topping) {
toppings.remove(topping);
}
}

public class PepperoniPizza extends Pizza {
public void addTopping(String topping) {
System.out.println(“Cannot add Toppings”);
}

public static void main(String[] args) {
Pizza pizza = new PepperoniPizza();
pizza.addTopping(“Mushrooms”);
pizza.removeTopping(“Peperoni”);
}
}

What is the result?

A.
Compilation fails.

B.
Cannot add Toppings

C.
The code runs with no output.

D.
A NullPointerException is thrown in Line 4.

Explanation:
Main.java:13: addTopping(java.lang.String) in PepperoniPizza cannot override addTopping(java.lang.String) in Pizza; overridden method is final
public void addTopping(String topping) {
^
Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error



Leave a Reply 2

Your email address will not be published. Required fields are marked *


Anuja

Anuja

Answer is A, since final method cannot be overridden.