240 likes | 389 Views
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
E N D
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 componentswhich can be modified as needed • Hierarchy of classes - inheritance
Without Inheritance • One way to represent classes Personname, dateOfBirth, wallet Studentname, dateOfBirth, wallet, gpa, dept, idCard, …
With Inheritance • Another way, using hierarchy/inheritance Personname, dateOfBirth, wallet Put shared things into parent class is_a Studentgpa, dept, idCard, …
Inheritance Hierarchy Personname, dateOfBirth, wallet is_a is_a Facultysalary, dept, officeHours … Studentgpa, dept, idCard, … is_a is_a UnderGrad… GradgradDate, …
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
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 • …
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; } }
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
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
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()
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() + … ; }
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
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!
Multiple-Inheritance • You can’t do this in Java! {Camera} {PhoneAndCamera} {Phone} Phone Camera PhoneAndCamera +takePhoto() +makeCall() +makeCall() +takePhoto()
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()
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
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
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}
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();
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.
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
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!
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}