Title: Inheritance, polymorphism
1Inheritance, polymorphism typing rules in Java
revision
or Everything you wanted to know about OOP but
were afraid to ask
- SOFTENG 251
- Object Oriented Software Construction
2Who I am
- Hong Yul Yang
- PhD candidate (another one)
- Software Engineering alumni 2000 2003
- Yes, I was just like you when I was, erm, younger
- Tutored for SoftEng courses (for a long time)
- Teaching stance
- Im learning from you just as much as youre
learning from me! - Tell me how youre finding the material
- How to contact me room 303.476 open door
hours email( hongyul_at_cs.auckland.ac.nz )
3Building 303, Room 476
476
Level 4
Me
Elevators
4Whats bothering you?
- Today is a catch-up lecture (no Generics yet)
- Are you really comfortable with the fundamental
OOP (Object-oriented programming) concepts? - Inheritance
- Polymorphism dynamic binding
- Typing rules really, what can a variable point
to? - Interfaces abstract classes
- I need to know what you dont know
- Im going to go slow til you get em
5Assumptions
- You are comfortable enough with object-based
programming - i.e. C structs objects
- You know
- How to write classes and define methods
- How to instantiate objects of a certain class
- How to invoke methods of an object
- The difference between instance and static
variables/methods - Basically part A of the assignment is under your
grasp - Uhh, right?
6Inheritance
public class Animal
(extends Object)
- Human extends Mammal
- i.e. Mammal is a superclass (aka parent) of Human
- What does this mean?
- Human is a Mammal but the opposite isnt
necessarily true! - Everything a Mammal does (methods) and have
(instance variables), a Human can too but again
the opposite isnt necessarily true! - Human also extends Animal, thus repeat above with
Animal
public class Mammal extends Animal
public class Human extends Mammal
Object
Animal
Mammal
Bird
Cat
Dog
Human
7Animal
public class Animal private int age 0
public Animal() System.out.println("animal
born") public void makeSound()
System.out.println("gibberish") public
void getOlder(int years) age years
public int getAge() return age
Animal
-age
makeSound() getOlder() getAge()
Animal animal new Animal() animal.getOlder(2)
System.out.println(animal.getAge()) animal.makeSo
und()
8Mammal
Animal
-age
public class Mammal extends Animal protected
String name public Mammal(String name)
this.name name public void makeSound()
System.out.print(name" goes ")
super.makeSound()
makeSound() getOlder() getAge()
overriding
Mammal
super is a special variable
name
- Every constructor must first call a constructor
from its superclass - If it doesnt, then Java implicitly calls an
empty super-constructorsuper() - protected means visible only to subclasses (and
classes within same package)
makeSound()
Mammal mammal new Mammal("Bambi") mammal.getOld
er(1) System.out.println(mammal.getAge()) mammal
.makeSound()
9Bird
Animal
-age
public class Bird extends Animal private int
age 10 public void fly()
System.out.println("Don't look down")
public int getAge() return age
??
makeSound() getOlder() getAge()
overriding
Mammal
Bird
name
-age
- If you dont define a constructor, Java
implicitly defines an empty constructor, which in
turn calls an empty super-constructor - Fields are not overridden, i.e. they belong
exclusively to their enclosing class
makeSound()
fly() getAge()
Mammal mammal new Mammal("Bambi") Bird bird
new Bird() Bird.getOlder(5) System.out.println(b
ird.getAge()) bird.makeSound() mammal.fly()
//?? bird.fly()
10Human
Animal
-age
public class Human extends Mammal public
Human(String name) super(name)
public void makeSound() int myAge age
myAge getAge() System.out.println("I'm "
name " and " myAge
" years old") public String lie()
return "I like you"
Explicit super-constructor
makeSound() getOlder() getAge()
??
Mammal
Bird
name
-age
makeSound()
fly() getAge()
protected access
Animal animal new Animal() Human human new
Human("Hong") human.getOlder(3) human.makeSound(
) animal.lie() //?? human.lie()
Human
makeSound() lie()
11Polymorphism
Animal
- Recall
- Human is a Mammal
- Everything a Mammal does (methods) and have
(instance variables), a Human can too - Similarly, Mammal is an Animal. thus Human is
an Animal
-age
makeSound() getOlder() getAge()
Human human new Human("Hong") Animal animalMan
human animalMan.getOlder(10) animalMan.makeSou
nd() Animal animal new Mammal("Whoa") animal.m
akeSound()
Polymorphism right there
Mammal
name
makeSound()
- But the opposite isnt necessarily true!
Human
Mammal noname new Animal() Animal animalMan
human animalMan.lie()
makeSound() lie()
12Polymorphism
Animal
- Summary
- Variable var declared as type (class) T can point
to any value declared as T or Ts subclass - Variable var declared as type T can access all
visible methods defined in T as well as all of
Ts superclasses - var cant point to any value declared as Ts
superclass, even if the values actual type is T
or Ts subclass - var cant access any method defined in Ts
subclass, even if vars actual type is Ts
subclass
-age
makeSound() getOlder() getAge()
Mammal
name
makeSound()
Human me new Human() Animal animal new
Animal() Animal polymorph me Human me2
polymorph //ERR polymorph.lie() //ERR
Human
polymorphs declared type is Animal, although the
actual type of the object it points to is of type
Human
makeSound() lie()
13Overriding dynamic binding
Animal
- So we know what methods we can call but how do
we know which (overridden) method actually gets
executed?
-age
makeSound() getOlder() getAge()
Human human new Human("Hong") Animal animalMan
human animalMan.getOlder(10) animalMan.makeSou
nd() Animal animal new Mammal("Whoa") animal.m
akeSound() Animal birdAnimal
bird birdAnimal.getOlder(7) System.out.println(b
irdAnimal.getAge())
what happens here?
and here?
Mammal
Bird
-age
name
makeSound()
fly() getAge()
what about here?
- Simple rule
- Depends on the actual type of the object the
variable points to - Regardless of the declared type
Human
makeSound() lie()
14Back to typing rules
- Every value has an associated type
- "hi" is of type String
- 23 is of type int
- new Mammal("Grr") is of type Mammal
- Every variable has a declared type, to which you
can assign any value of type compatible with the
declared type - double ratio 0.22ratio is declared as type
double, and it holds a value of type double - double rounded 235rounded is declared as type
double, but you can assign a value of type int to
it. Why? int is essentially a subtype of double - What does compatible mean? Simple X is compatble
with Y if X Y or X is a subtype of Y (for
objects, subtype subclass)
15To whom can you assign stuff?
- Easy rule
- You can directly assign anything up the
hierarchy - long intdouble longObject MammalAnimal
HumanGeneral Specific - Incompatible
- Mammal ? Object
- Bird ? Dog
double
Object
float
Animal
assign
long
Mammal
Bird
int
Dog
Human
16Different means of assignment
Human dude new Human("Orig") Animal cloned
clone(dude)
original dude i.e. Mammal Human
cloned return value i.e. Animal Mammal
public Mammal clone(Mammal original) Human
human new Human("Ayee") human.getOlder(origi
nal.getAge()) return human
return value human i.e. Mammal Human
17Assinging downstream (downcasting)
- You cant do this for obvious reasons
Animal animal new Bird() //ALLOWED Dog dog
animal //NAH!
Object
Animal animal new Dog() //ALLOWED Dog dog
animal
Animal
??
- Makes sense, but still not allowed by
compiler.But this is
Mammal
Bird
Animal animal new Dog() Dog dog (Dog)animal
//Downcasting
Animal animal new Bird() Dog dog (Dog)animal
Dog
Human
- The above compiles! (why?)
18Summary
Animal
- So what do we get out of all this?
-age
Mammal zoo new Mammal3 zoo0 new
Dog("Fido") zoo1 new Cat("Mimi") Human
primate new Human("Primate") primate.getOlder(2
0) zoo2 primate makeNoise(zoo)
makeSound()
polymorphic assignments
polymorphic parameter-passing
Mammal
name
public void makeNoise(Animal animals) for
(int i 0 i lt animals.length i)
animalsi.makeSound()
makeSound()
dynamic method dispatch (binding)
Human
Cat
Dog
makeSound()
makeSound()
makeSound() lie()
19Motivations for using inheritance
- Extending in the literal sense specialisation
without re-inventing the wheel
Human
Superman
-strength
makeSound() lie()
fly() seeThrough()
- Refactoring an existing design by extracting
common traits
Mammal
Human
Bird
-age name
-age
-age name
makeSound() getOlder() getAge()
makeSound() getOlder() getAge() lie()
makeSound() getOlder() getAge() fly()
- When you sense repetition among classes refactor
them into hierarchy!
20Abstract methods
- Sometimes we want the general class to represent
a common operation, but the details of the
operation varies depending on subclasses - All animals must eat, but how they eat should
depend solely on their exact species
Animal
public abstract class Mammal extends Animal
... //does not override eat()
public abstract class Animal ... public
abstract void eat()
-age
makeSound() getOlder() getAge()eat()
public class Bird extends Animal ... public
void eat() //something different
public class Human extends Mammal ...
public void eat() System.out.println("Wine
n dine")
21Abstract classes
- Abstract methods are essentially blank methods
that are up to subclasses to fill in (override) - If a class has one or more abstract methods, then
it must be declared abstract - Naturally, you cant instantiate an abstract
class - But you can call abstract methods just as you
call normal methods
Animal a new Bird() a.eat() //there
- Also, if a subclass does not override all of the
abstract methods of its superclass, then the
subclass becomes an abstract class itself
public abstract class Mammal extends Animal
... //does not override eat()
22Templating using abstract methods
- Redefining Mammals makeSound() to be of the
form - ltnamegt is ltagegt year(s) old and says to you
'ltsoundgt' - name and age are fixed but ltsoundgt varies
according to specific subclass - See code demo
23Java Interfaces
- Interfaces are special classes whose methods
are all abstract - i.e. über-abstract classes if you will
- One major distinction a class can extend
(implement) multiple interfaces - So what good is a class with no real methods?
- Interfaces are useful for defining a signature,
or a contract of its implementing classes - i.e. the methods in the interface define what the
implementing class should do, i.e. expected to do - Also a cheap way of supporting multiple
inheritance - Example java.util.List is an interface that
defines what a list is supposed to do, and
ArrayList and LinkedList actually implement these
contracts
24Flyer interface
- All birds can fly so can some mammals
- But you cant extend from both mammals and bird ?
introduce a Flyer interface
public interface Flyer public void fly()
public class Bird extends Animal implements Flyer
public void fly() System.out.println("Do
nt look down")
Flyer ltltinterfacegtgt
fly()
Mammal
public class FlyingSquirrel extends
Mammal implements Flyer public void fly()
System.out.println("Yay!!")
FlyingSquirrel
Bird
name
-age
Flyer flyer new FlyingSquirrel() flyer.fly() f
lyer new Bird() flyer.fly()
fly() makeSound()
fly() getAge()
25More Interface facts
- In a Java interface, you
- can only define public abstract
methods(actually, even if its not explicitly
declared public or abstract, Java automatically
makes it so) - cant define instance variables
- can only define public, static and/or final
variables - Rules of inheritance and polymorphism apply to
interfaces just as they do to normal classes - e.g. an interface can inherit from another
interface!
public interface FastFlyer extends Flyer
public void hyperdrive()
- Class implementing FastFlyer must implement both
fly() and hyperdrive()
26Coming up
- Tutorial tomorrow?
- Lab on Thursday 3rd April, 10am 12pm
- Assignment 1 due
- Friday session 4th April Assignment 1
post-mortem - Can group 4 please see me before Friday to
discuss your post-mortem? - Assignment 2 is out
- Due 24th April (Week 7 after the break)
- Ill give you a brief demo soon
27Epilogue...
28Why OOP? Why Java?
- Truth is you can write anything in a procedural
language (C) - Hell, you can write anything in assembly language
- But youd rather program in C than assembly
right? Why? - Useful abstractions (statements, loops,
functions, structs) - Object-oriented languages provide even further
abstractions (classes, class hierarchy) that
naturally map to concepts in the real world - Java is a great platform for appreciating the
usefulness and power of OOP
29The truth about software development
- The big bang approach to writing programs is sooo
60s - Dont even bother trying to get it right the
first time - You are not the only one writing the program
- Up to thousands of people can be working on the
same system - What does this mean?
- You must always program with the future in mind
- Is my code going to be easy to modify and extend?
- You must always program with other programmers in
mind - Can they understand my code?
- Can even I understand my own code?
30So
- What makes a good program?
- Easy to understand
- Easy to extend and/or modify
- Easily adaptable to other purposes (reusable)
- Less likely to fail miserably because of a silly
mistake (robust) - Etc, etc
- Really, if we didnt care about any of the above,
we might as well write everything in machine code - I mean, it looks badass
- 1011010001010101010101110100100001001010110101
- But were not training you to be hackers!
31Java API classes Good OOP
- API Application Programmers Interface
- Its really a collection of programs (aka
library) with the sole purpose of being reused by
Java programmers (aka you) - Notice how each class has a clearly defined role
and purpose - String represents a sequence of characters and
has operations (methods) for doing various nice
things with it - Vector represents a growable list of items and
has operations for manipulating the list - Classes from the Java API are no different from
the classes you create ? they arent anything
special - Learn from them!