Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS102 – OOP Inheritance & Polymorphism David Davenport.

Similar presentations


Presentation on theme: "CS102 – OOP Inheritance & Polymorphism David Davenport."— Presentation transcript:

1 CS102 – OOP Inheritance & Polymorphism David Davenport

2 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

3 One way to represent classes Without Inheritance Person name, dateOfBirth, wallet Student name, dateOfBirth, wallet, gpa, dept, idCard, …

4 Another way, using hierarchy/inheritance With Inheritance Person name, dateOfBirth, wallet Student gpa, dept, idCard, … is_a Put shared things into parent class

5 Inheritance Hierarchy Person name, dateOfBirth, wallet Student gpa, dept, idCard, … is_a Faculty salary, dept, officeHours … is_a UnderGrad … Grad gradDate, … is_a

6 {Student} gpa dept idCard Inheritance & Composition {Person} name dateOfBirth wallet {Wallet} owner cash {IDCard} name idNo picture has_a is_a or has_a UML Person Student Wallet IDCard Object

7 Inheritance All classes extend Object class unless otherwise specified Sub-classes can Add new properties & methods … Object Person Student WalletIDCard LiseUndergradGrad parent/super class child/sub class

8 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; }

9 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 properties Have direct access to non- private properties & methods of parent classes With additional properties Student is_a Person

10 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)

11 {DiscountCD} getPrice() still returns 50 Overriding Methods Change getPrice()… getPrice() getTitle() getPrice() now returns 45 instead of 50 Object {MusicCD} 50 price getPrice() Best of Q title getTitle() 10 discount getDiscount() getPrice() getDiscountedPrice()

12 The MusicCD Class class 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() + … ; }

13 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

14 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!

15 {PhoneAndCamera} Multiple-Inheritance You can’t do this in Java! Phone +makeCall() {Phone} +makeCall() {Camera} +takePhoto() Camera +takePhoto() PhoneAndCamera

16 {PhoneAndCamera} Single-Inheritance so you have to do this in Java Phone +makeCall() {Phone} +makeCall() {Camera} +takePhoto() Camera +takePhoto() PhoneAndCamera +takePhoto() camera.takePhoto() camera +takePhoto()

17 Use super to call parent constructor e.g. super( ___, ___, ___ ); to refer to parent methods e.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.

18 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

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

20 Extended Type Checking Distinguish type of reference vs. type of object Compiler checks only the reference type! Objecto; Personp; Students; 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. 

21 Extended Type Checking Can now match object of type or sub-type Distinguish type of reference vs. type of object Objecto;// can hold anything Personp;// can hold Person, Student, … Students;// only Student and sub-classes p = new Person( _____); s = new Student( ____); p.getName(); s.getName(); s.getGPA(); p.getGPA(); ( (Student) p ).getGPA(); 

22 Extended Type Checking Can now match object of type or sub-type Distinguish type of reference vs. type of object Objectx;// can hold any Object, MusicCD… MusicCDy;// can hold MusicCD, DiscountCD… DiscountCDz;// 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.

23 POLYMORPHISM “I did it my way”

24 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

25 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();//doesm s.m();//doesm’ g.m();//doesm’’ any.m(); // depends on object type!

26 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!

27 Misc… Java access/visibility Modifiers public protected same package & sub-classes default same package only private Restricting inheritance the final (key)word…


Download ppt "CS102 – OOP Inheritance & Polymorphism David Davenport."

Similar presentations


Ads by Google