Copyright @ 2009-2011 Dr. Milica Barjaktarovic
All Rights Reserved
Chapter 11
Inheritance and Polymorphism
Table of Contents
1. Inheritance and Polymorphism
This is what makes OO interesting.
Inheritance is useful when there is a common set of characteristics for many different classes. This “base set” becomes the superclass, or base class.
Other classes can inherit this basic set and also add their own unique methods and fields. Such classes are called subclasses, or derived classes.
Subclass “is-a” instance of superclass, i.e. a special case of the superclass.
Examples: conceptually
Bee IS an insect. Cricket IS an insect. Cockroach IS an insect. Moskito IS an insect. Etc.
Superclass
Subclass
Subclass
Subclass
Subclass
Insect: hasAntenae liesEggs
Bee hasWings eats Honey canBuzz canFly canSting Cricket canJump canChirp eats? Cockroach hasWings canFly canCrawl eatsHumanFood
Moskito
hasWings canFly eatsBlood canBuzzz canInfect
Dog has4Feet hasTail hasWhiskers hasFur hasLongNose canBark
GoldenRetreiver isLarge isSilky
Chiuaua
isSmall isNotFuzzy Malamute isLarge hasThickFur
Pomeranian isSmall hasLongFur hasBushyTail Cat has4feet hasTail hasWhiskers hasFur hasFlatFace canMeow
Persian isFluffy isSmall isHome Siamese hasBlueEyes isNotFuzzy hasBeigeBodywithBrownTrim isSmall isHome Tabby hasStripes isSmall isHalfWild Tiger isLarge hasStripes isWild How to code inheritance
The base class and all derived classes are “classes as usual”. What connects them is that all derived classes must have “extends” clause in the declaration. public class Leopard extends Cat public class Siamese extends Cat public class Tabby extends Cat
If we don’t put the word “extend”, by default every class in Java inherits from Object class, i.e. by default, every class is specified as whatever_access class Name extends