1 CS2200 Software Development Polymorphism II A. O’Riordan, 2008 K. Brown, 2004-2007.

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
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.
CPSC150 Inheritance Details Chapter 9. CPSC150 Print in Entertainment ver 2 (with inheritance): public void print() { System.out.print("title: " + title.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 CS2200 Software Development Lecture 29: Polymorphism I A. O’Riordan, 2008 Based on notes by K. Brown.
CPSC150 Abstract Classes and Interfaces Chapter 10.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Java Interfaces Overview Java Interfaces: A Definition.
UML Class Diagram: class Rectangle
Abstract Classes and Interfaces
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
OVERRIDING/OVERLOADING Srinivas. EXAM OBJECTIVES  Given a code example, determine if a method is correctly overriding or overloading another method,
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
1 Abstract Classes “I prefer Agassiz in the abstract, rather than in the concrete.” CS Computer Science II.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Programming in Java CSCI-2220 Object Oriented Programming.
Abstract Classes. Review PA – 3 Design Considerations /Web/CS239/programs/pa3/draft.php ?harrisnlCS239
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance and Design CSIS 3701: Advanced Object Oriented Programming.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
Inheritance ndex.html ndex.htmland “Java.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
OOP Basics Classes & Methods (c) IDMS/SQL News
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance & Method Overriding BCIS 3680 Enterprise Programming.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
BY:- TOPS Technologies
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Inheritance and Polymorphism
More inheritance, Abstract Classes and Interfaces
Polymorphism.
METHOD OVERRIDING in JAVA
CS18000: Problem Solving and Object-Oriented Programming
Chapter 9 Carrano Chapter 10 Small Java
Chapter 14 Abstract Classes and Interfaces
Chapter 11 Inheritance and Encapsulation and Polymorphism
Topics OOP Review Inheritance Review Abstract Classes
Presentation transcript:

1 CS2200 Software Development Polymorphism II A. O’Riordan, 2008 K. Brown,

2 Example: Camera Store Write a program to manage the inventory of a camera shop ●all inventory elements contain a description of the item, a catalogue number, the quantity in stock, and the price ●lenses have a focal length, and they may zoom ●films have a recommended storage temperature, a speed, and a number of exposures ●cameras have a maximum shutter speed, a body colour, and may come complete with a lens

Class Design: version 1 ●Represent each type of inventory element as a class ●each inventory element should be able to display details, and should allow the user to change the stock levels, change the price, etc -description: String -catalogueNumber: int -stockLevel: int -price: double -focalLength: double -zoom: boolean +Lens(...) +display() +changePrice() +changeStock() -description: String -catalogueNumber: int -stockLevel: int -price: double -temp: int -exposures: int +Film(...) +display() +changePrice() +changeStock() -description: String -catalogueNumber: int -stockLevel: int -price: double -hasLens: boolean -maxShutterSpeed: int -bodyColour: String +Camera(...) +display() +changePrice() +changeStock() Lens Film Camera

4 Class Design: version 2 ●Each inventory element has some details in common, but also some different properties... ●define a superclass for all elements ●define subclasses for each new type ●inherit common data and methods ●define new data and methods in subclasses ●Issue: Should we have a “type” variable in the superclass? ●Represent the inventory as an array of the superclass objects ●Why not three separate arrays? ●What happens if we want to add a new type of stock?

5 UML Class diagram -focalLength: double -zoom: boolean +Lens(...) +display() -temp: int -exposures: int +Film(...) +display() -hasLens: boolean -maxShutterSpeed: int -bodyColour: String +Camera(...) +display() Lens Film Camera #description: String #catalogueNumber: int #stockLevel: int #price: double +InventoryItem(...) +changePrice() +changeStock() InventoryItem +: public #: protected -: private +: public #: protected -: private Accessible? public: anywhere protected: in same class or subclass private: in same class Accessible? public: anywhere protected: in same class or subclass private: in same class

Outline class definitions: InventoryItem variables will be inherited by subclasses public class InventoryItem { protected String description; protected int catalogueNumber; protected int stockLevel; protected double price; public InventoryItem(String desc, int cat, int stock, double pr) { description = desc; catalogueNumber = cat; if (stock > 0) stockLevel = stock; else stockLevel = 0; if (pr > 0) price = pr; else price = 0.0; } assume proper comments and other methods assume proper comments and other methods

public class Lens extends InventoryItem { private double focalLength; private boolean zoom; public Lens(String desc, int cat, int st, double p, double length, boolean hasZoom) { super(desc, cat, st, p); if (length > 0) focalLength = length; else focalLength = 0.0; zoom = hasZoom; } public String display() { return "# " + catalogueNumber + "\n" + description + "\nin stock: " + stockLevel + "\nfocal length = " + focalLength; } able to access these, since " protected " subclass constructor first statement must be call to superclass constructor

8 Try Displaying the Inventory InventoryItem[] inventory = new InventoryItem[3]; //filling the array manually inventory[0] = new Lens(...); inventory[1] = new Film(...); inventory[2] = new Lens(...); for (int i = 0; i < inventory.length; i++) System.out.println(inventory[i].display()); //error Does not compile! Why? Hint: Where is display method defined and what reference is used to call it.

9 Fixing Problem ●Also doesn't compile: InventoryItem item = new Lens(...); System.out.println(item.display()); ●Compiler sees that the variable item is of type InventoryItem. InventoryItem has no method display(). Therefore it complains, and does not compile. ●Object in question is actually of type Lens, and so it does have the appropriate method ●Solution: give the InventoryItem class a display() method (even though we know it will not be called)

10 New class diagram new method, which will be overridden public class InventoryItem { protected String description;... public void display() { } } description: String catalogueNumber: int stockLevel: int price: double //... +display() InventoryItem -focalLength: double -zoom: boolean +display() -temp: int -exposures: int +display() Lens Film...

11 Polymorphic display InventoryItem[] inventory = new InventoryItem[3]; //filling the array manually inventory[0] = new Lens(...); inventory[1] = new Film(...); inventory[2] = new Camera(...); for (int i = 0; i<inventory.length; i++) System.out.println(inventory[i].display()); Display method is now polymorphic - it has a different form in each subclass. JVM will find the appropriate method at run-time, i.e. it does the work for you

12 Abstract classes ●When writing the inventory example, we never intended to create an object directly of class InventoryItem - we would only create objects of the classes Lens, Film or Camera. ●Therefore InventoryItem should be an abstract class ●If we declare a class to be abstract, Java will not allow any program to create an object of that class directly - we will be forced to define a non-abstract subclass, and create objects in that. ●Non-abstract classes are called concrete classes. ●We can still create references to objects of an abstract class.

13 Example abstract class definition public abstract class InventoryItem { public String description; //... //display() - will be overriden public String display() { return "dummy"; } } Declares InventoryItem to be abstract - we are now forbidden from creating an object of this class directly.

14 Example: trying to instantiate an abstract class public class AbstractTest { public static void main(String args[]) { InventoryItem test = new InventoryItem("",1,1,1.0); } Trying to create an object from an abstract class -Called Compiler C:\PROGRA~1\Java\JDK15~1.0_0\bin\javac.exe- -Target File: \AbstractTest.java- \AbstractTest.java:18: InventoryItem is abstract; cannot be instantiated InventoryItem test = new InventoryItem("", 1, 1, 1.0); ^ 1 error -Finished-

15 Abstract methods ●We can also declare a method to be abstract. An abstract method has no method body. ●If a method is abstract, it means that any concrete subclass must provide a definition of the method. ●If we declare any method to be abstract, Java forces us to declare the class to be abstract. ●This ensures we can't forget to provide a method definition for a concrete class

16 Example: not defining an abstract method public class AbstractMethodTest extends InventoryItem { int dummy; } D:\MyData\Java\ADDRES~2\AbstractMethodTest.java:2: AbstractMethodTest should be declared abstract; it does not define display() in InventoryItem 1 error Output window: No definition for display() public abstract class InventoryItem { public abstract void display(); } Abstract method, no method body

17 Example: abstract method in concrete class public class InventoryItem { public String description; //display() - will be overriden public abstract void display(); } D:\MyData\Java\ADDRES~2\InventoryItem.java:10: InventoryItem should be declared abstract; it does not define display() in InventoryItem 1 error Output Window Abstract method, but not an abstract class

18 Why use Abstract classes? Declaring a class to be abstract is good programming practice: ●if we don't intend to create an object directly from a class, then declaring it to be abstract forces us to respect this ●if we want to create polymorphic methods at the lower levels, instead of providing a method body which we don't intend to use, declare the method to be abstract. This also forces us to provide a method for the subclasses - Java won't let us forget.

19 Final methods and classes If we declare a method to be final, then it cannot be overridden in any subclass. e.g. public final String displayName() {... We can still invoke calls to the method in a subclass, but it will not be polymorphic. If we declare a class to be final, then it cannot be extended - i.e. we cannot create subclasses of a final class. e.g. public final class Friend {...