1 / 24

CS102 – OOP

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

rianna
Download Presentation

CS102 – OOP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 componentswhich can be modified as needed • Hierarchy of classes - inheritance

  3. Without Inheritance • One way to represent classes Personname, dateOfBirth, wallet Studentname, dateOfBirth, wallet, gpa, dept, idCard, …

  4. With Inheritance • Another way, using hierarchy/inheritance Personname, dateOfBirth, wallet Put shared things into parent class is_a Studentgpa, dept, idCard, …

  5. Inheritance Hierarchy Personname, dateOfBirth, wallet is_a is_a Facultysalary, dept, officeHours … Studentgpa, dept, idCard, … is_a is_a UnderGrad… GradgradDate, …

  6. Inheritance & Composition is_a or has_a {Student}gpadeptidCard {Person}namedateOfBirthwallet {Wallet}ownercash has_a Object UML Person {IDCard}nameidNo picture Wallet has_a Student IDCard

  7. parent/superclass Object Person Wallet IDCard child/subclass Student Lise Undergrad Grad Inheritance • All classes extend Object class unless otherwise specified • Sub-classes can • Add new properties & methods • …

  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. Example Java Code Student is_a Person 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; } } With additional properties Call parent constructor to save writing code again! Additional methods for new properties Have direct access to non-private properties & methods of parent classes

  10. Inheritance (again) • All classes extend Object class unless otherwise specified • Sub-classes can • Add new properties & methods • Change function of existing methods (Override existing methods by adding ones with same signature) Object MusicCD CDCollection DiscountCD

  11. Overriding Methods Best of Q titlegetTitle() price getPrice() 50 • Change getPrice()… {MusicCD} Object getTitle() discountgetDiscount() 10 getPrice() {DiscountCD} getPrice() still returns 50 getPrice() now returns 45 instead of 50 getPrice()

  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() intgetDuration() String toString() Plus a whole lot more… public String toString() { return getTitle() + getPrice() + … ; }

  13. Example Java Code Defaults to “extends Object” public class DiscountCDextends MusicCD { int discount; public DiscountCD( __, __, theDiscount ) { super( ___, ___, ___); discount = theDiscount; } public double getDiscount() { return discount; } public double getPrice() { return price – price * discount / 100; } } Adds new property 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

  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. Multiple-Inheritance • You can’t do this in Java! {Camera} {PhoneAndCamera} {Phone} Phone Camera PhoneAndCamera +takePhoto() +makeCall() +makeCall() +takePhoto()

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

  17. Super keyword • 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 Only useable inside class like this public String toString() { return super.toString() + “\t” + discount;} Note: super.super… is not allowed

  18. super vs. this super this super refers to non-private constructors, properties & methods in parent class Person this refers to properties & methods in current class Student super this

  19. Extended Type Checking • Can now match object of type or sub-type • Distinguish type of reference vs. type of object Object x; Person y; Student z; x = y; x = z; y = new Person( _____); z = new Student( ____); y = z; z = y; z = (Student) y; ref obj Need typecast since not all objects that y can refer to are necessarily Students or descendants as required for z to refer to them. {ref. type} {obj. type}

  20. Extended Type Checking • Can now match object of type or sub-type • Distinguish type of reference vs. type of object Object x; // can hold anything Person y; // can hold Person, Student, … Student z; // only Student and sub-classes y = new Person( _____); z = new Student( ____); y.getName(); z.getName(); z.getGPA(); y.getGPA(); ( (Student) y ).getGPA();

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

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

  23. m X {Person} any {Person} {Person} m Y {Student} m’ {Student} m m’ Z {Grad} m’’ {Grad} Polymorphism • Everyone does it their way! x.m(); // does m y.m(); // does m’ z.m(); // does m’’ any.m(); // depends on object type!

  24. m m m m’’’ m’ m’ m m’ {Student} {Student} {Faculty} m’’ {Grad} Polymorphic collections • Objects in a collection all do it their way! for each person p in uni do p.m(); uni {Person[]} m oops! {Person}

More Related