CS102 – Data Structures Lists, Stacks, Queues, Trees & HashTables. David Davenport.
CS102 – OOP Inheritance & Polymorphism David Davenport.
-
Upload
curtis-eugene-barnett -
Category
Documents
-
view
249 -
download
0
Transcript of CS102 – OOP Inheritance & Polymorphism David Davenport.
CS102 – OOP
Inheritance& Polymorphism
David Davenport
Introduction Advantages of OOP
Natural view/description of world• Set of interacting objects
organised in classes
& facilitates reuse• Classes are reusable components
which can be modified as needed
Hierarchy of classes - inheritance
One way to represent classes
Without Inheritance
Personname, dateOfBirth, wallet
Studentname, dateOfBirth, wallet, gpa, dept, idCard, …
Another way, using hierarchy/inheritance
With Inheritance
Personname, dateOfBirth, wallet
Studentgpa, dept, idCard, …
is_a
Put shared things into
parent class
Inheritance Hierarchy
Personname, dateOfBirth, wallet
Studentgpa, dept, idCard, …
is_a
Facultysalary, dept, officeHours …
is_a
UnderGrad…
GradgradDate, …
is_a is_a
{Student}gpadept
idCard
Inheritance & Composition
{Person}name
dateOfBirthwallet {Wallet}
ownercash
{IDCard}nameidNo
picture
has_a
has_a
is_aor
has_a
UMLPerson
StudentWallet
IDCard
Object
Inheritance
All classes extend Object class unless otherwise specified
Sub-classes can Add new properties
& methods …
Object
Person
Student
Wallet IDCard
Lise Undergrad Grad
parent/superclass
child/subclass
Example Java Code
public class Person {
String name;Date dateOfBirth;Wallet wallet;
public Person ( String name, Date dob) {this.name = name;dateOfBirth = dob;wallet = null;
}
public String getName() {return name;
}}
public class Student extends Person {
double gpa;String dept;IDCard id;
public Student ( String name, Date dob, IDCard id, String dept) {
super( name, dob);this.id = id;this.dept = dept;gpa = 0;
}
public double getGpa() {return gpa;
}}
Example Java Code
Call parent constructor to
save writing code again!
Additional methods for new
propertiesHave direct access to non-
private properties & methods of parent classes
With additional properties
Student is_a
Person
Inheritance (again)
All classes extend Object class unless otherwise specified
Sub-classes can Add new properties
& methods
Object
MusicCD
DiscountCD
CDCollection
Change function of existing methods (Override existing methods by adding ones with same signature)
{DiscountCD}
getPrice()still
returns 50
Overriding Methods Change getPrice()…
getPrice()
getTitle()
getPrice() now returns 45
instead of 50
Object
{MusicCD}
50price getPrice()
Best of QtitlegetTitle()
10discountgetDiscount()
getPrice()
getDiscountedPrice()
The MusicCD Classclass MusicCD
// properties…String albumTitle;String artist;double price;Track[] tracks;
// constructors…public MusicCD()public MusicCD( String title, String artist,
double price, Track[] theTracks)
// methods…String getTitle()double getPrice()int getDuration()String toString()
Plus a whole lot more…
public String toString() {return getTitle() + getPrice() + … ;
}
Example Java Code
public class DiscountCD extends MusicCD {
int discount;
public DiscountCD( __, __, theDiscount ) {super( ___, ___, ___);discount = theDiscount;
}
public double getDiscount() {return discount;
}
public double getPrice() {return price – price * discount / 100;
}}
Defaults to “extends Object”
Call parent constructor to save writing code again!
Overrides method with same
signature in parent class
Direct access to non-private properties &
methods of parent classes
Adds new property
Sub-class Constructors Call to parent (super) constructor must be first
statement in constructor (Java builds instances in layers, inside to out)
If omitted Java automatically calls defaults constructor (one with no param’s)
Note: Java classes can only have one parent.
Java is a single-inheritance language, as opposed to a multiple-inheritance language (such as C++) which can have many parents!
{PhoneAndCamera}
Multiple-Inheritance You can’t do this in Java!
Phone+makeCall()
{Phone}+makeCall()
{Camera}+takePhoto()
Camera+takePhoto()
PhoneAndCamera
{PhoneAndCamera}
Single-Inheritance so you have to do this in Java
Phone+makeCall()
{Phone}+makeCall()
{Camera}+takePhoto()
Camera+takePhoto()
PhoneAndCamera
+takePhoto() camera.takePhoto()
camera
camera+takePhoto()
Use super to call parent constructore.g. super( ___, ___, ___ );
to refer to parent methodse.g. implement toString() in DiscountCD
& to access parent properties(only needed if property with same name is defined in sub-class)
e.g. super.price
Super keyword
public String toString() {return toString() + “\t” + discount;
}
Note: super.super… is not allowed
Only useable inside class
like this
super.
super vs. this
Person
Student
thissuper
super refers to non-private constructors, properties & methods in parent class
this refers to properties & methods in current class
thissuper
EXTENDED TYPE CHECKING“What’s what?” & “What compiles?”
Extended Type Checking Distinguish type of reference vs. type of object Compiler checks only the reference type!
Object o;Person p;Student s;
p = new Person( _____);s = new Student( ____);
p = s;
s = p;
s = (Student) p;
refobj
{obj. type}
{ref. type}
o = p;o = s;
Need typecast since not all objects that p can refer to are necessarily
Students or descendants, as required for s to refer to them.
Extended Type Checking Can now match object of type or sub-type Distinguish type of reference vs. type of object
Object o; // can hold anythingPerson p; // can hold Person, Student, …Student s; // only Student and sub-classes
p = new Person( _____);s = new Student( ____);
p.getName();
s.getName();
s.getGPA();
p.getGPA();
( (Student) p ).getGPA();
Extended Type Checking Can now match object of type or sub-type Distinguish type of reference vs. type of object
Object x; // can hold any Object, MusicCD…MusicCD y; // can hold MusicCD, DiscountCD…DiscountCD z; // only DiscountCD and sub-classes
y = new MusicCD( _____);y = new DiscountCD( ____);
z = (DiscountCD) y; // ok if y is DiscountCD at runtime!
Need typecast since not all objects that y can refer to are necessarily DiscountsCD’s or descendants
as required for z to refer to them.
POLYMORPHISM“I did it my way”
Polymorphic Method Calls Method calls are based on object type, not reference type
e.g. MusicCD’s getPrice() is overridden in DiscountCD
MusicCD y = new MusicCD( _____);double thePrice = y.getPrice();
MusicCD y = new DiscountCD( ____);double thePrice = y.getPrice();
This calls the getPrice() method in DiscountCD, not
the one in MusicCD
Polymorphism Everyone does it their way!
m
m
m’
m’’
m
m’
p{Person}
s{Student}
g{Grad}
{Person}
{Student}
{Grad}
any{Person}
p.m(); // does m s.m(); // does m’g.m(); // does m’’
any.m(); // depends on object type!
Polymorphic collections Objects in a collection all do it their way!
uni{Person[]}
m
m’
{Student}
m
m’
m’’
{Grad}
m
m’
{Student}
m
m’’’
{Faculty}
for each person p in uni do p.m();
m
{Person}
oops!
Misc… Java access/visibility Modifiers
public protected
• same package & sub-classes default
• same package only private
Restricting inheritance the final (key)word…