Title: Java Lecture 5
1Java Lecture 5
- CS 1311X
- Our Story So Far
- The Story of O
- Inheritance, Polymorphism and Death in the
Afternoon
13X11
2Our Story So Far
- Object Oriented Programming Features
- Encapsulation
- Reusability
- Adaptability
- Object Oriented Programming Benefits
- Generic "Drop In" Components
- Modeling Real World Objects
- Handling Collections Easily
3Our Story So Far
- Java Language Syntax
- Class Structure
- Fields
- Constructors
- Methods
- Accessors
- Modifiers
- Special Concepts
- toString
- main
- static
4Our Story So Far
- All objects are manipulated using references
5The Story of O
6The Story of O
7The Story of O
- Operator Overloading
- int a 3
- int b 2
- int c
- String x "Hello "
- String y "World!"
- String z
- c a b
- z x y
8The Story of O
- Other Overloading
- Constructor
- public Student(String name, double gpa)
- public Student(String name)
- Method
- public int max(int a, int b)
- public int max(int a, int b, int c)
- public int max(short a, short b)
-
9The Story of O
- Overriding
- Also called redefinition
- class A
- int someMethod()
-
- class B extends A
- int someMethod()
-
10The Story of O
11Inheritance
- class Animal
-
- String name
- public Animal(String name)
-
- this.name name
-
-
-
12Inheritance
- class Dog extends Animal
-
- int fleas
- public Dog(String name, int fleas)
-
- super(name)
- this.fleas fleas
-
-
-
13Inheritance
- class Cat extends Animal
-
- int hairBalls
- public Cat(String name, int hairBalls)
-
- super(name)
- this.hairBalls hairBalls
-
-
-
14Inheritance (Deceptive Diagram)
Animal
Dog
Cat
15Inheritance (True Diagram)
Object
Animal
Dog
Cat
16Truth Be Known
- Class Object exists
- It defines lots of useful methods
- e.g. toString
- see the API
- Thus every class is either
- a direct subclass of Object (no extends)
- or
- a subclass of a descendant of Object (extends)
- So what?
17Motivation
- Repetitive tasks
- Collections of things (objects)
- Baseball cards
- Library items
- Shapes
- Animals
- Vehicles
- Students
18Motivation
- Collections are seldom uniform
- Desire method of holding a collection of
dissimilar items - Need to change the type mismatch rules
19Recall
- float f
- double d
- int i
- String s
- CokeMachine cm
- f d // illegal
- d f // legal
- i d // illegal
- d i // legal
20Recall
- float f
- double d
- int i
- String s
- CokeMachine cm
- f (float)d // legal
- d f // legal
- i (int)d // legal
- d i // legal
21Recall
- float f
- double d
- int i
- String s
- CokeMachine cm
- s cm // illegal
- cm s // illegal
22Recall
- float f
- double d
- int i
- String s
- CokeMachine cm
- s (String)cm // illegal
- cm (CokeMachine)s // illegal
23Inheritance Changes the Rules
Object
Animal
Dog
Cat
24Inheritance Changes the Rules
- Object o
- Animal a
- Dog d new Dog()
- Cat c new Cat()
- d c // illegal
- a c // OK, a Cat is an Animal
- o c // OK, a Cat is an Object
- o a // OK, an Animal is an Object
- a o // Illegal, not all Objects are Animals
- d a // Illegal, not all animals are Dogs
- Confusing?
25The Keyword is Extends
- Object creation process
- 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
26Step by Step
Dog d
27Step by Step
Dog d new Dog()
public Dog()
28Step by Step
Dog d new Dog()
public Dog()
public Animal()
29Step by Step
Dog d new Dog()
public Dog()
Object
public Animal()
public Object()
30Step by Step
Dog d new Dog()
public Dog()
Object
Animal
public Animal()
31Step by Step
Dog d new Dog()
public Dog()
Object
Animal
Dog
32Step by Step
Dog d new Dog()
Object
Animal
Dog
33Step by Step
Dog d new Dog()
Object
Animal
"A Dog Object"
Dog
34Quizlette
Animal a new Dog()
Object
Animal
"A Dog Object"
Dog
35Quizlette
Object o new Dog()
Object
Animal
"A Dog Object"
Dog
36Quizlette
Dog d new Animal()
Object
Animal
"An Animal Object"
ILLEGAL
37Quizlette
Animal a new Object()
Object
"An Object Object"
ILLEGAL
38Quizlette
Dog d new Object()
?
39Quizlette
Dog d new Object()
Object
"An Object Object"
ILLEGAL
40Same Logic
d o
?
o d
OK!
?
41Don't be confused!!!
- Primitives
- double d
- float f
- d f // legal...no loss of information
- f d // illegal...potential loss of
- // information
42Don't be confused!!!
- References
- Object o
- Dog d
- o d // legal (a dog is an object)
- d o // illegal (all objects are not
- // dogs)
- Note Not the same as primitives...they are all
just references!!!
43Warning
- When you break the aforementioned rules...
- Java sometimes tells you that a cast is required
- Even if it's a real bad idea
- Pearls p
- Swine s
- p (Pearls)s
44What's the Point?
- 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.
45Dynamic Binding
- The heart of polymorphism
- Assume Animal and Dog have a toString method
- Object o new Dog()
- Animal a new Dog()
- Dog d new Dog()
- o.toString()
- a.toString()
- d.toString()
- ((Object)o).toString()
Object
Object
Animal
Object
Animal
Dog
46Dynamic Binding
- It even works like this...
A Dog Object
Ref Animal
a
Animal a new Dog() a.toString()
47Trick 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.
48Reference/Method Checking
- 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.
49More Quizlette Fun
- Object o new Dog()
- Animal a new Dog()
- Dog d new Dog()
- o.toString()
- o.move()
- o.bark()
- a.toString()
- a.move()
- a.bark()
- d.toString()
- d.move()
- d.bark()
o
a
d
50Back to Collections
Object
51Java Collections
- LinkedList
- ArrayList
- Vector
- Stack
- HashSet
- TreeSet
- HashTable
- Plus you'll write lots on your own...
- They all hold objects!
52Using Generic Collections -- Poorly
- LinkedList zoo new LinkedList()
- Object o new Dog()
- Pig p new Pig()
- zoo.add(o)
- zoo.add(new Cat())
- zoo.add(p)
- while(zoo.size() gt 0)
- o zoo.removeFirst()
- if(o instanceOf Dog)
- ((Dog)o).bark()
- if(o instanceOf Cat)
- ((Cat)o).meow()
- if(o instanceOf Pig)
- ((Pig)o).oink()
53Can We Do Better?
Object
54Using Generic Collections -- Betterly???
- LinkedList zoo new LinkedList()
- Object o new Dog()
- Pig p new Pig()
- zoo.add(o)
- zoo.add(new Cat())
- zoo.add(p)
- while(zoo.size() gt 0)
- o zoo.removeFirst()
- o.talk() // Does this work???
55Using Generic Collections -- Betterly???
- LinkedList zoo new LinkedList()
- Object o new Dog()
- Pig p new Pig()
- zoo.add(o)
- zoo.add(new Cat())
- zoo.add(p)
- while(zoo.size() gt 0)
- o zoo.removeFirst()
- ((???))o.talk() // Does this work???
56Mystery Partially Solved
57Using Generic Collections -- Correctly
- LinkedList zoo new LinkedList()
- Animal a new Dog()
- Object o new Dog()
- Pig p new Pig()
- zoo.add(a)
- zoo.add(o)
- zoo.add(new Cat())
- zoo.add(p)
- while(zoo.size() gt 0)
- o zoo.removeFirst()
- ((Animal))o.talk()
58Software Engineering
- What should the talk method in class Animal do?
- public void talk()
-
- /
- Make sure you redefine this method in
- your individual animal subclasses
- /
59How many will forget?
60Solution Abstract Methods and Classes
- class Animal
-
- public abstract void talk()
- // Note No body!
-
- Result Error!!!
Sometimes called a deferred method...
61Solution Abstract Methods and Classes
- abstract class Animal
-
- public abstract void talk()
- // Note No body!
-
- Result Okay.
62Java Never Forgets
- Any subclass of class Animal has two choices
- 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).
63Concrete
- class Dog extends Animal
-
- public void talk()
-
- bark()
-
64Or
- class Dog extends Animal
-
- public void talk()
-
- System.out.println("Bow wow!)
-
65Just for the Record
- abstract class Canine
-
- // define other stuff?
-
Object
abstract Animal abstract talk()
abstract Canine
Cat talk()
Pig talk()
Dog talk()
Wolf talk()
66Using Generic Collections -- Correctly
- LinkedList zoo new LinkedList()
- Animal a new Dog()
- Object o new Dog()
- Pig p new Pig()
- zoo.add(a)
- zoo.add(o)
- zoo.add(new Cat())
- zoo.add(p)
- while(zoo.size() gt 0)
- o zoo.removeFirst()
- ((Animal))o.talk()
Object
abstract Animal abstract talk()
67Design Guidelines
- Class hierarchy design is important
- Move common methods up the tree
- Use abstract methods appropriately
- May be iterative process
- Container classes should generally hold Objects
- Learn and understand the Java rules concerning
- Type checking
- Reference checking
- Dynamic binding
- You'll be glad you did!
68Back to the Problem at Hand
69Coke Machines Available
- CokeMachine
- Standard Model
- Requires Exact Change
- Low Cost
70Coke Machines Available
- CokeMachine2000
- Deluxe Model
- Makes Change
- Intermediate Cost
71Coke Machines Available
- CokeMachineUA
- (Urban Assault)
- Secure Model
- Makes Change
- High Cost
- Tamper Proof
72The Vending Machine Hierarchy
VendingMachine vend() load() vandalize()
toString()
CokeMachine2000 vend() vandalize()
toString()
CokeMachine vandalize() toString()
CokeMachineUA vandalize() toString()
abstract
73The Players
- Students
- Normally have change dollar bills
- Instructors
- Just have change (and not much of that)
- Deans
- Have lots of money
- If machine is out of coke, will vandalize machine
74The Players
Person interact() toString()
Student interact()
Instructor interact()
Dean interact()
abstract
75Algorithm
- 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
- Allow them to interact (capture statistics)
- If the person is still living
- Enqueue them back into population
- Enqueue machine
- If time for service
- Randomly select and service one machine
76The Simulation
p.interact(v)
p
v
population
machines
if still alive
77Heart of Simulation
- p (Person)population.removeFirst()
- v (VendingMachine)machines.removeFirst()
- result p.interact(v)
- statsresult 2
- if(result gt -1)
-
- population.addLast(p)
-
- else
-
- System.out.println("Another one bites the
dust!") -
- machines.addLast(v)
78Without Polymorphism?
- Imagine what would have to happen in interaction
without polymorphism -
if Student if CokeMachine else if
CokeMachine2000 else if CokeMachineUA else if
Instructor if CokeMachine else if
CokeMachine2000 else if CokeMachineUA elseif
Dean if CokeMachine else if
CokeMachine2000 else if CokeMachineUA
79Service
- if((time SERVICE) 0)
-
- int chg
- int random
- int siz machines.size()
- VendingMachine vs
- random (int)(siz Math.random())
- vs (VendingMachine)machines.get(random)
- vs.load(CASE)
- chg STARTUPCHANGE - vs.getChange()
- chg vs.addChange(chg)
- startup chg
-
80Demo
81(No Transcript)
82(No Transcript)