- "sortable" would be an interface because it describes the abilities/behaviors that a sortable object must have (e.g., a method called
sort()) - "shape" would probably be an abstract class because shapes are objects in themselves that all share certain methods AND properties (e.g.,
numberOfSides,calculateArea(), etc.) - abstract classes can have properties, while interfaces can't
- design patterns are "common solutions to common problems"
- they're tried-and-true ways to organize classes and behaviors
- you have a fixed algorithm that does different things for different types
- a method takes objects of any class that implements some interface and calls a method defined in that interface
- that method calls a different version of the interface method depending on the specific subclass/type of the object being passed in
- only some animals fly, so don't put
fly()in anAnimalclass - also, you should try to avoid creating interfaces just to force the creation of a method/action
- a change in a superclass/interface shouldn't break the subclasses
- use strategy pattern
- create an interface
Flieswithflies() - create two classes that implement
Flies, one calledCanFlyand one calledCantFly - add an instance of
FlycalledflyingTypetoAnimal - then write a method
tryToFly()that callsflyingType.fly() - you can also add
setFlyingAbility()toAnimalso you can change the flying type for each animal - all the subclasses of
Animal, you can now setflyingTypeto an instance of whicheverFliessubclass is appropriate
- create an interface
- this doesn't break old classes and allows us to add multiple types of flying (e.g., can fly, can't fly, can flap, can fly when it reaches a certain age, etc.)
- interfaces reduce coupling and code duplication by allowing all classes that implement the same interface to be used by the same methods
- instead of writing a different method for each class, you can write one that takes in arguments of the interface type