The execution result of the following code:
import java.util.ArrayList;class Pizza{ ArrayList toppings; public final void addTopping(String topping){ toppings.add(topping); } public void removeTopping(String topping){ toppings.remove(topping); }}class PepperoniPizza extends Pizza{ public void addTopping(String topping){ System.out.println("Cannot add Toppings"); } public void removeTopping(String topping){ System.out.println("Cannot remove pepperoni"); }}public class Test{ public static void main(String[] args){ Pizza pizza = new PepperoniPizza(); pizza.addTopping("Mushrooms"); pizza.removeTopping("Pepperoni"); } }
This question examines the knowledge related to inheritance and rewriting. However, the final keyword is involved here.
I checked the knowledge points related to the final Keyword:
1. The final modified member variables must explicitly specify the initial values;
2. The final modified class member variables must specify the initial values in the declared variables or static initialization blocks;
3. The final modified instance member variables must specify the initial values when declaring variables or non-static initialization blocks or constructors;
4. The final modified member variables cannot be assigned a new value once they are assigned an initial value;
5. The final modified member variables cannot be accessed before the specified initial values (before initialization;
6. Local variables modified by final. Because the system does not initialize local variables, local variables must be explicitly initialized. Therefore, when using final to modify a local variable, you can specify the initial value during definition, or you can not specify the initial value. Similarly, final-modified local variables cannot be assigned a new value once they are specified. It is worth mentioning that the final modified parameters are not allowed to be assigned values in the final modified parameters;
7. reference type variables modified by final. The reference type variable stores only one reference address. Using final can only ensure that the address saved by the variable does not change, but the objects saved in the address can change;
8. The final method cannot be overwritten. If you do not want subclass to override a method of the parent class, you can use final to modify this method;
9. The final-modified class cannot have child classes. To ensure that a class cannot be inherited, you can use final to modify the class.
For example, the addtopping method in the pizza class in the question cannot be overwritten. An exception is reported during rewriting.
Scjp test preparation-8