Java Programming: From the Ground Up

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
Advertisements

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.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
ITEC200 – Week03 Inheritance and Class Hierarchies.
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.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
Chapter 7 - Generalization/Specialization and Inheritance1 Chapter 7 Generalization/Specialization and Inheritance.
C++ fundamentals.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Programming With Java ICS Chapter 8 Polymorphism.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
Java Programming: From the Ground Up
Chapter 10 Inheritance and Polymorphism
Lecture 2 Software Concepts Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
10 Polymorphism. 2 Contents Defining Polymorphism Method Overloading Method Overriding Early Binding and Late Binding Implementing Polymorphism.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
Classes - Intermediate
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)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
1 More About Derived Classes and Inheritance Chapter 9.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Web Design & Development Lecture 9
Inheritance and Polymorphism
Chapter 5 Hierarchies IS-A associations superclasses subclasses
Programming Language Concepts (CIS 635)
ATS Application Programming: Java Programming
Object Oriented Programming
Java Programming Language
Chapter 9: Polymorphism and Inheritance
Advanced Java Topics Chapter 9
Fundamental Error Handling
Inheritance Inheritance is a fundamental Object Oriented concept
Java Programming, Second Edition
Polymorphism.
Inheritance.
Chapter 9 Carrano Chapter 10 Small Java
CIS 199 Final Review.
Chapter 11 Inheritance and Polymorphism Part 1
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Computer Science II for Majors
Presentation transcript:

Java Programming: From the Ground Up Chapter 13: Polymorphism

Polymorphism Polymorphism is the third fundamental concept of OOP. In contrast to inheritance, polymorphism underscores the differences of class behavior in an inheritance hierarchy.

Ad-hoc Polymorphism – Method Overloading The code segment overloads the constructor of a Song class. The constructor is polymorphic; the constructor has three forms. public class Song { private String composer; private String lyricist; public Song () // default constructor composer ="" ; lyricist = ""; } public Song(String name) // same person wrote words and music composer =name ; lyricist = name; public Song (String name1, String name2) // two songwriters composer =name1; lyricist = name2; // other Song methods go here....... Method overloading, a form of polymorphism, is also known as ad-hoc polymorphism.

elvis = new HoundDog(); Upcasting Upcasting in an inheritance hierarchy allows an object of a derived type to be considered an object of a base type. Dog elvis; elvis = new HoundDog(); elvis = new Beagle(); elvis = new Bassett();   Because a HoundDog is-a Dog, a HoundDog reference can be upcast to Dog (line 2). Similarly, a Beagle reference and a Bassett reference can also be considered Dog references (lines 3 and 4). The reference elvis is polymorphic, i.e., elvis has “many forms” and elvis can refer to a Dog object, a HoundDog object, a Beagle object, or a Bassett object.

Dynamic (or Late) Binding A third form of polymorphism, dynamic or late binding, accentuates the behavioral differences among objects of different classes in a hierarchy. This is in contrast to inheritance, which exploits the similarities of classes.

The Shape Hierarchy Each class of the Shape hierarchy encapsulates a different geometrical shape. Some typical shapes are: ***** Square % %% %%% %%%% %%%%% RightTriangle # # # # # # # # # # # # # # # Triangle

The Shape Hierarchy Problem Statement: Design classes Square, RightTriangle, and Triangle that encapsulate three geometrical shapes. Each class should implement a method void draw (int x, int y) that “draws” a square, a right triangle, or an equilateral triangle (a triangle with three equal sides), respectively. The parameters x and y specify the relative position of the figure: y lines down and x spaces across from the current position of the screen cursor. The instance variables of each class are: int rows, the number of rows that comprise the figure, and char character, the keyboard character used for drawing the figure.

The Shape Hierarchy Java Solution: There is much the same about the three classes: the attributes are the same, and except for the draw(...) method, the getter and setter methods are the same. Factor out the commonality of the classes into one (abstract) superclass, Shape, which serves as a base class in an inheritance hierarchy that includes Square, RightTriangle, and Triangle.

The Shape Hierarchy The Shape hierarchy

The Shape Hierarchy The abstract class Shape has the following form: public abstract class Shape { protected int rows; // figure drawn on rows rows protected char character; // the drawing character   public Shape() rows = 0; char character = ' '; } public Shape(int x, char ch) rows = x; character = ch; public int getRows() return rows; public char getCharacter() return character; public void setRows(int y) rows = y; public void setCharacter(char ch) public abstract void draw(int x, int y); // must be implemented in concrete subclasses

The Shape Hierarchy public class Square extends Shape { public Square() // call Shape default constructor super(); } public Square(int x, char ch) { // call Shape 2 argument constr. super(x,ch); public void draw(int x, int y) // move down y lines for ( int i = 1; i <= y; i++) System.out.println(); // for each row for (int len = 1; len<= rows;len++) { // indent x spaces for (int i = 1; i <= x; i++) System.out.print(' '); for(int j = 1; j <=rows; j++) System.out.print(character); System.out.println(); public class RightTriangle extends Shape public RightTriangle() public RightTriangle(int x, char ch) // call Shape 2 argument constr. // move down y lines for ( int i = 1; i <= y; i++) System.out.println(); // for each row for (int len = 1; len<= rows; len++) //indent x spaces for (int j = 1; j <= len; j++) System.out.print(character); public class Triangle extends Shape public Triangle () public Triangle (int x, char ch) for(int len=1; len<=rows; len++) //indent; the vertex is centered for(int i=0; i <= rows-len+x; i++) System.out.print(" "); for(int i =1; i<=len; i++) System.out.print(character +" " ); } }

The Shape Hierarchy Problem Statement: Devise a test class that interactively queries a user for one of three shapes and subsequently draws the requested shape. Java Solution: The main(...) method of the following test class, requests input 1, 2, or 3 representing a square, a right triangle or an equilateral triangle, respectively. Because a Square is-a Shape, a RightTriangle is-a Shape, and a Triangle is-a Shape, all references are upcast to Shape

The Shape Hierarchy import java.util.*; public class TestDraw { public static void main(String[] args) Scanner input = new Scanner(System.in); Shape shape = null; // all references can be upcast to Shape int shapeNumber; //code number for each type of figure System.out.print("Enter 1: Square, 2: RightTriangle, 3: Equilateral Triangle: "); shapeNumber = input.nextInt();   switch (shapeNumber) case 1 : shape = new Square(4,'*'); //size 4, draw with * break; case 2 : shape = new RightTriangle(5,'#'); //size 5, draw with # case 3 : shape = new Triangle(6,'+'); //size 6, draw with + default : System.out.println("Invalid entry"); // shapeNumber is not 1,2, or 3 System.exit(0); // bad data, terminate the application } shape.draw(1,1);

The Shape Hierarchy Discussion: The application runs as you might expect, but only because Java implements polymorphism through late binding. On line 22, it appears that a Shape object (shape) invokes its draw(…) method. Shape is an abstract class, so no Shape object can exist. Shape does not implement draw(...) as part of the Shape class, draw(...) is declared abstract.   Which draw(...) method is invoked? The reference variable shape could refer to a Square object (line 13), a RightTriangle object (line 15), or a Triangle object (line 17).

The Shape Hierarchy When TestDraw is compiled and translated into bytecode, the Java compiler cannot determine which draw(…) method is applicable. The compiler knows that shape refers to a kind of Shape, but it does not know which kind. The appropriate draw(...) method is not discernible until the program runs and the user chooses one of three shapes. Consequently, the compiled version of the program, i.e., the bytecode that executes on the Java Virtual Machine, does not specify which draw(...) method is appropriate. The choice of the correct draw(...) method is postponed until the program executes; that is, the choice is postponed until runtime. Polymorphism via dynamic or late binding refers to choosing the appropriate method not at compile time, but at runtime. When the TestDraw application runs, Java determines which form of draw(...) to execute.

How Dynamic Binding Works The reference variable shape is declared to be of type Shape: Shape shape Shape is the apparent type or declared type of shape. A Shape object cannot be instantiated because Shape is an abstract class. The variable shape can refer to a Square object or a Triangle object, or an object of any concrete class that extends Shape.

How Dynamic Binding Works The real type or actual type of a reference variable is the type of the object that is created by the new operation. The real type of shape is Square, RightTriangle, or Triangle, depending on user input. Assume that the user, TestDraw, chooses to draw a right triangle. In this case, the real type of shape is RightTriangle. When the draw(...) method is invoked by shape, Java begins searching for a fully implemented draw(...) method. The search begins in the RightTriangle class (the real type of shape). If the RightTriangle class has implemented a draw(...) method then the search ends, and that method is called. If not, then Java searches the parent of RightTriangle. Searching continues all the way up the hierarchy until an implemented draw(...) method is found (or until the Object class is reached). Java uses late binding for all method invocations except final, private, and static methods.

Polymorphism Makes Programs Extensible Polymorphism allows you to generalize your classes with ease. Problem Statement: Expand the Shape class with a subclass, EmptySquare, that implements a draw method, which produces a square that is not filled. ***** * * * * * * *****

Polymorphism Makes Programs Extensible Java Solution: class EmptySquare extends Shape { public EmptySquare() super(); // calls default Shape constructor }   public EmptySquare(int x, char ch) super(x,ch); // call 2-argument Shape constructor public void draw(int x, int y) // move down y lines for ( int i = 1; i <= y; i++) System.out.println(); // for each row for (int len = 1; len<= rows; len++) // indent x spaces for (int i = 1; i <= x; i++) System.out.print(' '); // print a character on an edge // print spaces in the interior for(int j = 1; j <=rows; j++) if (j ==1|| j==rows || len==rows || len == 1 ) // on edge System.out.print(character); else System.out.print(" ");