If your class is not intended to be inherited, it should be final. You have to be very careful to make sure that you understand how the methods to be overridden in a subclass that was not intended for the inheritance function, in order to understand how to modify them.
Specific example:
You have a class that manages a list of names ...
public class MyNameManager { private List<String> numbers = new LinkedList<String>(); public void add(String value) { numbers.add(value); } public void addAll(Collection<String> values) { for(String value : values) { add(value); } } public void remove(String value) {
Now say that you want to create a new subclass that also counts the total number of times the name is added to the list, for example:
public class MyCountingNameManager extends MyNameManager { private int count = 0; @Override protected void addAll(Collection<String> values) { count += values.size(); super.addAll(values); } @Override protected void add(String value) { count += 1; super.add(value); } }
Seems pretty simple, no? But consider the result of the following:
MyCountingNameManager m = new MyCountingNameManager(); m.add("bob"); m.add("Sally");
The score is now 2, and all is well. But if we did the following:
List<String> family = new List<String>(); family.add("mom"); family.add("dad"); family.add("brother"); MyCountingNameManager m = new MyCountingNameManager(); m.add(family);
The score is now 6, not 3, which you probably expect. This is because calling addAll adds the size of the collection of values (3) to the account, and then calls the super.addAll method to do the actual processing. super.addAll through the collection and calls the add method for each value. But since we are working with MyCountingNameManager and not a MyNameManager , each time the method is called, it overrides add in the subclass. The MyCountingNameManager.add method, which runs, also increments the counter! Thus, each name is counted twice!
I believe this example comes from Effective Java. You should definitely find a copy and read the elements listed in Viele's answer in order to better understand some cases where inheritance is poorly suited.
Tom tresansky
source share