1 / 29

CS102 – OOP_2

CS102 – OOP_2. Inheritance, Polymorphism, Interfaces & Abstract classes . David Davenport. Abstract Classes & Methods. Motivation Do not want to include instances of common (base) class in polymorphic collection Want guarantee all objects in a polymorphic collection include certain methods.

zasha
Download Presentation

CS102 – OOP_2

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_2 Inheritance, Polymorphism, Interfaces & Abstract classes. David Davenport

  2. Abstract Classes & Methods Motivation Do not want to include instances of common (base) class in polymorphic collection Want guarantee all objects in a polymorphic collection include certain methods

  3. {Rectangle} {Rectangle} {Circle} Get into Shapes… • A collection of Rectangles & Circles? Ensure instances of TwoDShape cannot be added to collection TwoDShape Rectangle Circle picture { ?? } { TwoDShape[] }

  4. University People… • Abstract vs. Concrete classes Person Staff Student Academic Non-Academic UnderGrad Grad Secretarial Security Cleaning

  5. Get into Shapes… • Compute area of collection of shapes Ensure instances of TwoDShape cannot be added to collection Need guarantee that all future classes implement getArea() TwoDShape +getArea() Rectangle +getArea() Circle +getArea() Triangle Polygon RightAngled Isosceles Equilateral

  6. Abstract Classes (& methods) • Abstract classes provide • common parent which cannot be instantiated • a guarantee sub-classes already haveor must implement certain methods • Create with keyword “abstract” e.g. public abstract class Media {…} (sub-class extends abstract class as normal) • Can include • Properties (& constructors!) • Implemented methods • Abstract methods (create with keyword “abstract” & no body) e.g. public abstract double getDuration();

  7. The MusicCD Collection Object toString(), clone(), … title, artist, price, tracks getTitle(), getArtist(), getPrice(), getDuration() MusicCD CDCollection Set of MusicCD getValue() getTotalDuration() DiscountCD Discount setDiscount(-) getPrice()

  8. The Media Hierarchy Object toString(), clone(), … Media price, title, getPrice(), getTitle() {abst} getDuration() Library Set of Media getValue() getTotalDuration() DVD MusicCD artist, tracks getDuration() Video length director getDuration() DiscountCD discountsetDiscount(-) getPrice()

  9. The Media Class Declare as abstract - cannot be instantiated public abstract class Media { String title; double price; public Media( String title, double price) { this.title = title; this.price = price; } public String getTitle() { return title; } public double getPrice() {return price; } public void setPrice( double newPrice) { price = newPrice; } public abstract int getDuration(); public String toString() { return title + "\t" + getPrice() + "\n"; } } Can includeconstants, properties constructors!, implemented & abstract methods abstract method – look, no body! Class must be abstract if it includes abstract methods

  10. The Video Class // Video // David, 23/3/02 public class Video extends Media { int length; String director; public Video( String title, String director, int length, int price) { super( title, price); this.length = length; this.director = director; } public int getDuration() { return length; } public String getDirector() { return director; } public String toString() { return "VIDEO " + super.toString(); } } Sub-class simply extends “abstract” parent as normal Calls parent constructor Implements required “abstract” method Overrides & reuses parent method

  11. Interfaces Motivation Provides a form of multiple-inheritance Guarantee specified methods exist Powerful design approach!

  12. Interfaces • An interface is the boundary between two systemsthrough which they connect/communicate • Often standardised Advantage: can change either side without affecting the other! SystemA SystemB interface

  13. Java Interfaces • Declare with public interface X {…} • restricted to constants & abstract methods only • cannot be instantiated • guarantees any implementing classhas specified methods (else cannot be instantiated) • Classes extend one class & implement interfaces e.g. public class U extends V implements X,Y,Z {…} • Can view as a special form of class so class U is_a V, is_a X, is_a Y, is_a Z i.e. a form of multiple inheritance

  14. Simple example… Define interfacewith abstract method public interface Pointable { public boolean contains( int x, int y); } public class Circle extends TwoDShape implements Pointable { int radius; public Circle( int radius) { super(); this.radius = radius; } public int getRadius() { return radius; } public boolean contains( int x, int y) { // set result true iff x,y inside circle... return result; } } Define classthat implements interface Required method...won’t compile if omitted

  15. Another example… • Multiple inheritance? SmartPhone is_a Phone is_a Computer is_a NetworkedDevice Brain is_a Computer is_a BiologicalDevice GasCooker is_a Cooker is_a GasDevice Notebook is_a Computer is_a ElectricalDevice is_a NetworkedDevice ElectricCooker is_a Cooker is_a ElectricalDevice Microwave is_a Cooker is_a ElectricalDevice

  16. One soln with interfaces Computer ElectricalDevice Cooker Brain Notebook Microwave ElectricCooker GasCooker

  17. Another soln with interfaces Computer ElectricalDevice Cooker Brain Notebook Microwave ElectricCooker GasCooker

  18. Interfaces… • as a form of multiple-inheritance public class U extends V implements X, Y, Z {U} V a; a = new V(); a = new U(); X b; b = new X(); b = new U(); b = a; b = (U) a; Y c; c = new U(); c = b; {U} {X} {V} c {Y} {Y} {Z} {V} b {X} a {V}

  19. Categorised Library… Simple: just add set/get category to base class… Object toString(), clone(), … Media price, title, getPrice() {abst} getDuration()set & getCategory() Library Set of Media getValue() getTotalDuration() listInCategory(cat) MusicCD artist, tracks getDuration() Video length director getDuration() DiscountCD discount setDiscount(-) getPrice()

  20. The Categories Interface // Categories // David, 23/3/02 public interface Categories { public final String COMEDY = "COMEDY"; public final String ADVENTURE = "ADVENTURE"; public final String CRIME = "CRIME"; public final String NONFICTION = "NONFICTION"; public final String ROCK = "ROCK"; public final String POP = "POP"; public final String CLASSICAL = "CLASSICAL"; public String getCategory(); public void setCategory( String c); } Declare interface (instead of class) Can only include constants & abstract methods Methods abstract by default!

  21. Media with Interface (1) Object toString(), clone(), … Categories Media price, title, getPrice() {abst} getDuration()set & getCategory() Library Set of Media getValue() getTotalDuration() listInCategory(cat) MusicCD artist, tracks getDuration() Video length director getDuration() DiscountCD discount setDiscount(-) getPrice()

  22. The Media Class • public abstract class Media implements Categories { • // include all // properties, constructors & methods • // as before.. • // ********************************* • // & add properties & methods • // to implement Categories interface • String category; • public String getCategory() { • return category; • } • public void setCategory( String c) { • category = c; • } • // ********************************* • } Class implements one or more interfaces by adding any necessary code

  23. Categories CatVideo setCategory() getCategory() Media with Interface (2) Object toString(), clone(), … Media price, title, getPrice() {abst} getDuration() Library Set of ?Categories? getValue() getTotalDuration() listInCategory(cat) Categories MusicCD artist, tracks getDuration()setCategory() getCategory() Video length director getDuration() DiscountCD discount setDiscount(-) getPrice()

  24. Media with Interface (3) • Moral: Design interfaces first! (a) (b) IMedia Media ICategories Library - initially: set of IMedia - later: set of ICategories

  25. Extending Interfaces (a) public interface IMedia { public int getPrice(); public int getDuration(); } public abstract classMedia implements IMedia { public int getPrice() {…} } public classLibrary { ArrayList<IMedia>() items; public int getValue () {…} public int getTotalDuration() {…} } public classVideo extends Media { public int getDuration() {…} } public interface ICategories extends IMedia { public String getCategory(); public void setCategory( String c); } public class CatVideo extends Video implements ICategories { public String getCategory() {…} public void setCategory( String c) {…} } public classLibrary { ArrayList<ICategories>() items; public int getValue () {…} public int getTotalDuration() {…} public void listInCategory( cat) {…} }

  26. Media with Interface (3) • Moral: Design interfaces first! (a) (b) IMedia Media IMedia ICategories ICategories ICatMedia Library - initially: set of IMedia - later: set of ICategories Library - initially: set of IMedia - later: set of ICatMedia

  27. Extending Interfaces (b) public interface IMedia { public int getPrice(); public int getDuration(); } public abstract classMedia implements IMedia { public int getPrice() {…} } public classLibrary { ArrayList<IMedia>() items; public int getValue () {…} public int getTotalDuration() {…} } public classVideo extends Media { public int getDuration() {…} } public interface ICatMedia extends IMedia, ICategories { } public interface ICategories { public String getCategory(); public void setCategory( String c); } public class CatVideo extends Video implements ICatMedia { public String getCategory() {…} public void setCategory( String c) {…} } public classLibrary { ArrayList<ICatMedia>() items; public int getValue () {…} public int getTotalDuration() {…} public void listInCategory( cat) {…} }

  28. Interface notes • Can’t create objects of interface type, only a type that implements it • Interfaces can extend interfaces (but not classes) to form a hierarchy separate from class one • Start design with interfaces! • Java provides “instanceof” operator to test object type (but use very sparingly) • See also “getClass()”

  29. Other notes… • Method access modifiersprotected vs. default(nothing specified) • “default” is package access only • “protected” is package, plus can be sub-classed from another package!

More Related