27
CS102 – OOP Inheritance & Polymorphism David Davenport

CS102 – OOP

  • Upload
    rianna

  • View
    62

  • Download
    1

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

Page 1: CS102 – OOP

CS102 – OOPInheritance& Polymorphism

David Davenport

Page 2: CS102 – OOP

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

Page 3: CS102 – OOP

Lots of repetition…

Without Inheritance

Personname, dateOfBirth, wallet

Studentname, dateOfBirth, wallet, gpa, dept, idCard, …

Facultyname, dateOfBirth, walletsalary, dept, officeHours …

Page 4: CS102 – OOP

Another way - little repetition, intuitive…

With Inheritance

Personname, dateOfBirth, wallet

Studentgpa, dept, idCard, …

is_a

Put shared things into

parent class

Page 5: CS102 – OOP

Inheritance Hierarchy

Personname, dateOfBirth, wallet

Studentgpa, dept, idCard, …

is_a

Facultysalary, dept, officeHours …

is_a

UnderGrad…

GradgradDate, …

is_a is_a

Page 6: CS102 – OOP

{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

Page 7: CS102 – OOP

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

Page 8: CS102 – OOP

Example Java Codepublic 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;

}}

Page 9: CS102 – OOP

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

Page 10: CS102 – OOP

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)

Page 11: CS102 – OOP

{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()

Page 12: CS102 – OOP

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() + … ;

}

Page 13: CS102 – OOP

Example Java Codepublic 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

Page 14: CS102 – OOP

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!

Page 15: CS102 – OOP

{PhoneAndCamera}

Multiple-Inheritance You can’t do this in Java!

Phone+makeCall()

{Phone}+makeCall()

{Camera}+takePhoto()

Camera+takePhoto()

PhoneAndCamera

Page 16: CS102 – OOP

{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()

Page 17: CS102 – OOP

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.

Page 18: CS102 – OOP

super vs. this

Person

Studentthissuper

super refers to non-private constructors, properties & methods in parent class

this refers to properties & methods in current class

thissuper

Page 19: CS102 – OOP

EXTENDED TYPE CHECKING“What’s what?” & “What compiles?”

Page 20: CS102 – OOP

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;

ref obj

{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.

Page 21: CS102 – OOP

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();

Page 22: CS102 – OOP

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.

Page 23: CS102 – OOP

POLYMORPHISM“I did it my way”

Page 24: CS102 – OOP

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

Page 25: CS102 – OOP

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!

Page 26: CS102 – OOP

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!

Page 27: CS102 – OOP

Misc… Java access/visibility Modifiers

public protected

• same package & sub-classes default

• same package only (package-private) Private

The “@Override” annotation

Restricting inheritance the final (key)word…