What are some easy-to-understand * bad * examples of using inheritance?

I am looking for bad examples of using inheritance. I am not very creative, so this was the best I could think of:

class Car : public Engine {} 

The car has an engine, but it is not an engine.

This will probably help explain the concept, but I think there are more illustrative examples?

+4
source share
4 answers

"Classic" example; -):

 public class Stack extends Vector { ... } 

The stack is not a vector.

If Stack extends Vector, you can insert / delete at each given index, while you need to allow adding / removing elements by pressing / popping.

+5
source

Use almost any example that uses inheritance without regard to the behavior of the base class.

A classic example is the relationship between Square and Rectangle . Of course, in math, a square is a type of rectangle. However, when developing software, a square does not behave like a rectangle:

 public class Rectangle { public virtual int Width { get; set; } public virtual int Height { get; set; } } public class Square : Rectangle { public override int Width { get { return base.Width; } set { base.Width = value; base.Height = value; } } public override int Height { get { return base.Height; } set { base.Height= value; base.Width = value; } } } 

If another Client class requires a Rectangle , but receives Square , the Client will be torn because it expects its Rectangle to have Width and Height , which do not affect each other.

+4
source

Inheritance is very useful, but also interrupts encapsulation. This means that your subclasses depend on the implementation details of the superclass; if the superclass changes, your subclass may break. Here is an example in Java, from Effective Java from Josh Bloch:

 public class InstrumentedHashSet<E> extends HashSet<E> { // number of attempted element insertions private int addCount = 0; public int getAddCount() { return addCount; } @Override public boolean addAll<Collection<? extends E> c) { addCount += c.size(); return super.addAll(c); } } 

The problem is that the hashSet addAll () method uses its add () method internally, but does not document this. Therefore, if you try

 InstrumentedHashSet<String> s = new InstrumentedHashSet<String>(); s.addAll(Arrays.asList("Snap", "Crackle", "Pop")); 

you get the score 6 instead of 3. In this particular case, this is not very harmful, but if you add a large collection or perform some other operation, it may be.

Thus, concrete classes are usually not a good idea for inheritance, unless they are designed for subclasses.

+1
source

This has been discussed for years, and you will find a lot of materials / discussions linking to the issue on google.

 public class Square extends Rectangle { ... } 

Perhaps not surprisingly, a square should not be inherited from a rectangle.

0
source

All Articles