inheritance polymorphism

82
13X11 13X11 Java Lecture 5 CS 1311X Our Story So Far The Story of O Inheritance, Polymorphism and Death in the Afternoon

Upload: sadiamuqaddas

Post on 15-Nov-2015

45 views

Category:

Documents


3 download

DESCRIPTION

Inheritance/ polymorphism

TRANSCRIPT

Java Lecture 113X11
13X11
13X11
public Student(String name)
public int max(int a, int b, int c)
public int max(short a, short b)
13X11
{
{
e.g. toString
a direct subclass of Object (no extends)
or
So what?
Need to change the type mismatch rules
13X11
Recall
Confusing?
13X11
Dog d = new Dog();
1. Create reference d
2. Start creating Dog by entering Dog constructor and making call to parent.
3. Start creating Animal by entering Animal constructor and making call to parent.
4. Create Object portion
5. Create Animal portion
6. Create Dog portion
f = d; // illegal...potential loss of
// information
13X11
d = o; // illegal (all objects are not
// dogs)
Note: Not the same as primitives...they are all just references!!!
13X11
Warning
Java sometimes tells you that a cast is required
Even if it's a real bad idea
Pearls p;
Swine s;
p = (Pearls)s;
Java Philosophy: Catch errors at compile time.
Leading to tricky concept #2: Dynamic Binding
At run time (dynamic) when a method is invoked on a reference the ACTUAL OBJECT is examined and the "lowest" or closest version of the method is actually run.
13X11
Object o = new Dog();
Animal a = new Dog();
Dog d = new Dog();
Animal a = new Dog();
Trick #3
Java checks types at compile time when assigning references (Run time checking is also performed).
Java always decides the method to be invoked by looking at the object at runtime.
At compile time Java checks method invocations to make sure that the reference type will have the correct method. This may appear contradictory to dynamic binding.
13X11
x.y();
x is a reference which has a type which is its class
That class (or a superclass) must have method y or a compile error will result.
13X11
They all hold objects!
public void talk()
* your individual animal subclasses
class Animal
abstract class Animal
Define a talk method (i.e. { })
Be abstract
Note: Abstract classes may not be used to instantiate or make objects (new)
References to abstract classes are legal (and quite desireable).
13X11
Concrete
Move common methods up the tree
Use abstract methods appropriately
May be iterative process
Learn and understand the Java rules concerning
Type checking
Reference checking
Dynamic binding
13X11
13X11
Instructors
Deans
13X11
Person
interact()
toString()
Student
interact()
Instructor
interact()
Dean
interact()
abstract
13X11
Algorithm
Create population of Students, Instructors and Deans adding each to population LinkedList
Create group of machines adding to machines LinkedList
Loop in time
Dequeue a person
Dequeue a machine
Enqueue them back into population
Enqueue machine
13X11
}
Imagine what would have to happen in interaction without polymorphism
if Student
if CokeMachine