Inheriting too much
After this: See a stack that inherits from a list break its own rule, fix it by holding the list, and say when inheritance still fits.
On this page · 5 sections · 3 checks
A is a pile: you push an item on top, and you pop the item on top. That is the whole rule. A list already stores items in order and can add and remove at the end. So why not make the stack a child of the list and add push? This lesson shows what that costs.
A stack that inherits from a list
The child gets every method of its parent. That is the point of inheriting, and here it is the problem.
class BadStack(list): def push(self, x): self.append(x)
s = BadStack()s.push(1)s.push(2)s.insert(0, 99)print(s.pop(), s[0])2 99
import java.util.Stack;
public class Main { public static void main(String[] args) { Stack<Integer> s = new Stack<>(); s.push(1); s.push(2); s.add(0, 99); System.out.println(s.pop() + " " + s.get(0)); }}2 99
In Python, BadStack inherits from list and adds one method, push. Follow the calls:
push(1)andpush(2)put 1, then 2, on the pile. The top is 2.- s.insert(0, 99)s.add(0, 99) puts 99 at position 0, which is the bottom of the pile. A stack should never allow that, but the method was inherited from the list, so it runs.
poptakes the top,2. The bottom of the pile is now99, an item that no push put there.
Java's own library made the same mistake. Its Stack class inherits from Vector, a list class, so add(0, 99) works on it too. The Java tab of the block above shows the same program with the library's Stack.java.util.Stack inherits from Vector, a list class. That is why add(0, 99) and get(0) work on it, and why this program prints 2 99.
The stack's rule, "only the top changes", can be broken by any caller who reaches for a list method. Nothing in the class stops them, because the class offers all of those methods itself.
A stack that holds a list
The fix is composition. SafeStack keeps a list in a private field and offers four methods: push, pop, peek and size. Each one passes the call on to the list.
- BadStack inherits from list
- SafeStack is made of 1 list (composition)
class SafeStack: def __init__(self): self._items = []
def push(self, x): self._items.append(x)
def pop(self): return self._items.pop()
def peek(self): return self._items[-1]
def size(self): return len(self._items)
t = SafeStack()t.push(1)t.push(2)print(t.pop(), t.size())2 1
import java.util.ArrayList;
class SafeStack { private ArrayList<Integer> items = new ArrayList<>();
void push(int x) { items.add(x); }
int pop() { return items.remove(items.size() - 1); }
int peek() { return items.get(items.size() - 1); }
int size() { return items.size(); }}
public class Main { public static void main(String[] args) { SafeStack t = new SafeStack(); t.push(1); t.push(2); System.out.println(t.pop() + " " + t.size()); }}2 1
Here the stack holds 1 and 2; pop returns 2, and then size is 1. Now try the bad line:
t.insert(0, 99)# AttributeError: 'SafeStack' object has no attribute 'insert't.add(0, 99);// error: cannot find symbolPython stops when it reaches the line, with an AttributeError: SafeStack has no method called insert.Java refuses before the program runs: the file does not compile, because SafeStack has no method add. The list is still inside, doing the storing, but nobody outside can reach it. The class offers only what a stack should do.
Add the line t.insert(0, 99)t.add(0, 99) before the print and run it again to see the error for yourself.
When inheritance is still right
None of this makes inheritance wrong. It fits when both of these are true:
- The "is a" sentence is true: a circle is a shape.
- The child wants everything the parent offers. Every method of
Shapemakes sense for a circle.
Your own error types are another good fit. class OutOfStock(Exception)class OutOfStock extends Exception is a true "is a": it is an error, and it should behave like every other error. The stack failed the second test: a stack is not a list with one more method, it is a list with most methods taken away.
Check yourself
Three pushes, then a list method that a stack should never offer. What does this print?
class BadStack(list): def push(self, x): self.append(x)
s = BadStack()s.push(5)s.push(6)s.push(7)s.insert(0, 42)print(s.pop(), s[0], len(s))import java.util.Stack;
public class Main { public static void main(String[] args) { Stack<Integer> s = new Stack<>(); s.push(5); s.push(6); s.push(7); s.add(0, 42); System.out.println(s.pop() + " " + s.get(0) + " " + s.size()); }}SafeStack holds a list instead of inheriting from one. What does it give up, and what does it gain?
Composition is not always the answer. Which of these is a good use of inheritance?
Honesty notes
- Say why a stack that inherits from a list can be broken: it offers every list method, including insert at the bottom.
- Predict what such a stack holds after an insert at position 0, and say that Java's own Stack has the same hole.
- Write a stack that holds a list in a private field and offers only push, pop, peek and size.
- Say when inheritance still fits: a true "is a" where the child wants everything the parent offers, such as shapes or error types.