CS102 – OOP_2 Inheritance, Polymorphism, Interfaces & Abstract classes. David Davenport.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
OOP: Inheritance By: Lamiaa Said.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Abstract Classes and Interfaces
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
CS102 – OOP Inheritance & Polymorphism David Davenport.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Lecture 3 Casting Abstract Classes and Methods Interfaces.
Polymorphism & Interfaces
CS 307 Fundamentals of Computer ScienceInterfaces and Abstract Classes 1 Topic 7 Interfaces and Abstract Classes “I prefer Agassiz in the abstract, rather.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
AP Computer Science A – Healdsburg High School 1 Interfaces, Abstract Classes and the DanceStudio - Similarities and Differences between Abstact Classes.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
© 2007 Lawrenceville Press Slide 1 Chapter 9 Inheritance  One class is an extension of another.  Allows a class to define a specialized type of an existing.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
1 More About Derived Classes and Inheritance Chapter 9.
Modern Programming Tools And Techniques-I
Inheritance ITI1121 Nour El Kadri.
Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Week 6 Object-Oriented Programming (2): Polymorphism
Interfaces.
Chapter 14 Abstract Classes and Interfaces
Chapter 8 Class Inheritance and Interfaces
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

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

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

University People… Abstract vs. Concrete classes Person Student GradUnderGrad Staff AcademicNon-Academic SecretarialSecurityCleaning

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

Abstract Classes (& methods) Abstract classes provide common parent which cannot be instantiated a guarantee sub-classes already have or 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();

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

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

The Media Class 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"; } Declare as abstract - cannot be instantiated Can include constants, properties constructors!, implemented & abstract methods abstract method – look, no body! Class must be abstract if it includes abstract methods

The Video Class // Video // David, 23/3/02 public class Video extends Media { intlength; Stringdirector; 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(); } Calls parent constructor Sub-class simply extends “abstract” parent as normal Implements required “abstract” method Overrides & reuses parent method

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

Interfaces An interface is the boundary between two systems through which they connect/communicate Often standardised System A System B Advantage: can change either side without affecting the other! interface

Java Interfaces Declare with public interface X {…} restricted to constants & abstract methods only cannot be instantiated guarantees any implementing class has 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

Simple example… public interface Pointable { public boolean contains( int x, int y); } public class Circle extends TwoDShape implements Pointable { intradius; 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 interface with abstract method Define class that implements interface Required method... won’t compile if omitted

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

One soln with interfaces NotebookBrain ComputerElectricalDevice MicrowaveElectricCookerGasCooker Cooker

Another soln with interfaces NotebookBrain ComputerElectricalDevice MicrowaveElectricCookerGasCooker Cooker

{V} a Interfaces… as a form of multiple-inheritance {U} {V} {Y} {Z} {X} b 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; public class U extends V implements X, Y, Z c {Y} {U}

Interfaces class U extends class V implements interfaces X,Y,Z Class U is_a V & is_a X & is_a Y & is_a Z class V interface X interface Y class U extendsimplements interface Z V a; a = new U(); X b; b = (U) a; Y c; c = new U(); Cannot instantiate an interface, but can put an implementing class into it

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

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!

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

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

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

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

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

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

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

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

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