Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Similar documents
Review for the. Final Exam. Final Exam. December 8, Final Format. Final Format. Ways to get an A on the Final. A Crash Course in Java

Inheritance -- Introduction

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 6 Reflection

ECE 122. Engineering Problem Solving with Java

Inheritance and Polymorphism

Polymorphism. Polymorphism is an object-oriented concept that allows us to create versatile software designs

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Programming in C# Inheritance and Polymorphism

Inheritance. Quick Review of Last Lecture. November 12, Passing Arguments. Passing Arguments. Variable Assignment Revisited

Polymorphism. Agenda

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

OVERRIDING. 7/11/2015 Budditha Hettige 82

Binghamton University. CS-140 Fall Dynamic Types

Anatomy of a Class Encapsulation Anatomy of a Method

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

ECE 122. Engineering Problem Solving with Java

Java Object Oriented Design. CSC207 Fall 2014

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Enhanced Class Design -- Introduction

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Big software. code reuse: The practice of writing program code once and using it in many contexts.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Lab 10: Inheritance (I)

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

First IS-A Relationship: Inheritance

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

What is Inheritance?

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14

Exercise: Singleton 1

Polymorphism. Arizona State University 1

File: D:\My Documents\Classes\Computer Science\Class Notes\Fall New\Polymorphism\Employee.java 7/20/1999, 10:53:52 AM

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

CS111: PROGRAMMING LANGUAGE II

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Example: Count of Points

More Relationships Between Classes

Example: Count of Points

ECE 122. Engineering Problem Solving with Java

Inheritance. Chapter 7. Chapter 7 1

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Packages & Random and Math Classes

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

C++ Important Questions with Answers

Java Fundamentals (II)

Introductory Programming Inheritance, sections

CS1020: DATA STRUCTURES AND ALGORITHMS I

S <: T Type compa*bility rela*on.

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

BBM 102 Introduction to Programming II

Object-Oriented Concepts

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Computer Science II (20073) Week 1: Review and Inheritance

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

Announcements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Chapter 5. Inheritance

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Inheritance and Polymorphism

Data Conversion & Scanner Class

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods

CS-202 Introduction to Object Oriented Programming

Instance Members and Static Members

Comp 249 Programming Methodology

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Chapter 11: Inheritance

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

CSEN401 Computer Programming Lab. Topics: Object Oriented Features: Abstraction and Polymorphism

Inheritance and Polymorphism

CS260 Intro to Java & Android 03.Java Language Basics

Programming II (CS300)

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Inheritance (an intuitive description)

Chapter 5 Object-Oriented Programming

Lecture 18 CSE11 Fall 2013 Inheritance

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

CSA 1019 Imperative and OO Programming

9/10/2018 Programming Data Structures Inheritance

Implements vs. Extends When Defining a Class

Object Orientated Programming Details COMP360

Chapter 10: Inheritance

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

BBM 102 Introduction to Programming II Spring 2017

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

CLASS DESIGN. Objectives MODULE 4

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

QUESTIONS FOR AVERAGE BLOOMERS

Inheritance and Polymorphism

Transcription:

Final Exam Polymorphism Time: Thursday Dec 13 @ 4:30-6:30 p.m. November 26, 2007 Location: Curtiss Hall, room 127 (classroom) ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor: Alexander Stoytchev Method Overloading The compiler determines which method is being invoked by analyzing the parameters Quick Review of Last Lecture float tryme(int x) return x +.375; [signature 1] tryme: int float tryme(int x, float y) [signature 2] tryme: int, float return x*y; Method Overriding public class Parent public float tryme(int x) return x +.375; public class Child extends Parent public float tryme(int x) return x*x; Same Signatures Different Method Bodies Overriding Methods A child class can override the definition of an inherited method in favor of its own The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked 1

Overriding A method in the parent class can be invoked explicitly using the super reference If a method is declared with the final modifier, it cannot be overridden Overloading vs. Overriding Overloading deals with multiple methods with the same name in the same class, but with different signatures The concept of overriding can be applied to data and is called shadowing variables Shadowing variables should be avoided because it tends to cause unnecessarily confusing code Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overloading vs. Overriding Overloading lets you define a similar operation in different ways for different parameters Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Business Overriding lets you define a similar operation in different ways for different object types RetailBusiness ServiceBusiness KMart Macys Kinkos Class Hierarchies Object the mother of all objects in Java Two children of the same parent are called siblings Common features should be put as high in the hierarchy as is reasonable An inherited member is passed continually down the line Therefore, a child class inherits from all its ancestor classes There is no single class hierarchy that is appropriate for all situations 2

The Object Class The equals method of the Object class returns true if two references are aliases We can override equals in any class to define equality in some more appropriate way As we've seen, the String class defines the equals method to return true if two String objects contain the same characters The designers of the String class have overridden the equals method inherited from Object in favor of a more useful version [http://www.holtsoft.com/java/resources/inherit_tutorial/inheritance/methods.jpg] Abstract Classes An abstract class is a placeholder in a class hierarchy that represents a generic concept public abstract class Animal abstract void makesound(); An abstract class cannot be instantiated We use the modifier abstract on the class header to declare a class as abstract: public abstract class Product // contents public class Cow extends Animal System.out.println("Moo-Moo"); public class Dog extends Animal System.out.println( Wuf-Wuf"); public class Duck extends Animal System.out.println( Quack-Quack"); Abstract Classes An abstract class often contains abstract methods with no definitions (like an interface) Unlike an interface, the abstract modifier must be applied to each abstract method Also, an abstract class typically contains nonabstract methods with full definitions A class declared as abstract does not have to contain abstract methods -- simply declaring it as abstract makes it so Abstract Classes The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract An abstract method cannot be defined as final or static The use of abstract classes is an important element of software design it allows us to establish common elements in a hierarchy that are too generic to instantiate 3

Interface Hierarchies Inheritance can be applied to interfaces as well as classes Other Stuff From Chapter 8 That is, one interface can be derived from another interface The child interface inherits all abstract methods of the parent A class implementing the child interface must define all methods from both the ancestor and child interfaces Note that class hierarchies and interface hierarchies are distinct (they do not overlap) This example shows how multiple inheritance can be faked in java Visibility Cartoon [http://www.vsj.co.uk/pix/articleimages/may05/javathread3.jpg] [http://faculty.juniata.edu/kruse/cs2/vis.gif] Visibility Revisited Visibility Revisited It's important to understand one subtle issue related to inheritance and visibility All variables and methods of a parent class, even private members, are inherited by its children As we've mentioned, private members cannot be referenced by name in the child class Because the parent can refer to the private member, the child can reference it indirectly using its parent's methods The super reference can be used to refer to the parent class, even if no object of the parent exists However, private members inherited by child classes exist and can be referenced indirectly 4

Chapter 9 Section 9.1 & 9.2 Polymorphism Polymorphism is an object-oriented concept that allows us to create versatile software designs Chapter 9 focuses on: defining polymorphism and its benefits using inheritance to create polymorphic references using interfaces to create polymorphic references using polymorphism to implement sorting and searching algorithms additional GUI components Polymorphism in Nature Binding Consider the following method invocation: obj.doit(); At some point, this invocation is bound to the definition of the method that it invokes If this binding occurred at compile time, then that line of code would call the same method every time However, Java defers method binding until run time -- this is called dynamic binding or late binding Late binding provides flexibility in program design [http://www.blackwellpublishing.com/ridley/images/h_erato.jpg] Polymorphism Polymorphism The term polymorphism literally means "having many forms" A polymorphic reference is a variable that can refer to different types of objects at different points in time The method invoked through a polymorphic reference can change from one invocation to the next All object references in Java are potentially polymorphic Suppose we create the following reference variable: Occupation job; Java allows this reference to point to an Occupation object, or to any object of any compatible type This compatibility can be established using inheritance or using interfaces Careful use of polymorphic references can lead to elegant, robust software designs 5

References and Inheritance An object reference can refer to an object of its class, or to an object of any class related to it by inheritance Polymorphism via Inheritance For example, if the Holiday class is used to derive a class called Christmas, then a Holiday reference could be used to point to a Christmas object Holiday Christmas Holiday day; day = new Christmas(); References and Inheritance Assigning a child object to a parent reference is considered to be a widening conversion, and can be performed by simple assignment Assigning a parent object to a child reference can be done also, but it is considered a narrowing conversion and must be done with a cast The widening conversion is the most useful Polymorphism via Inheritance It is the type of the object being referenced, not the reference type, that determines which method is invoked Suppose the Holiday class has a method called celebrate, and the Christmas class overrides it Now consider the following invocation: day.celebrate(); If day refers to a Holiday object, it invokes the Holiday version of celebrate; if it refers to a Christmas object, it invokes the Christmas version Example: Animals class hierarchy You can use jgrasp to draw diagram like this one Animal.java Cow.java Duck.java Dog.java Farm.java 6

public class Cow extends Animal System.out.println("Moo-Moo"); public abstract class Animal abstract void makesound(); public class Dog extends Animal System.out.println( Wuf-Wuf"); public class Duck extends Animal System.out.println( Quack-Quack"); public class Farm public static void main(string[] args) Cow c=new Cow(); Dog d=new Dog(); Duck k= new Duck(); Result: Moo-Moo Wuf-Wuf Quack-Quack c.makesound(); d.makesound(); k.makesound(); public class Farm2 public static void main(string[] args) Animal[] a = new Animal[3]; public abstract class Animal abstract void makesound(); public void move() System.out.println( walk ); Define a new method which is not abstract and is inherited by all children. Result: Moo-Moo Wuf-Wuf Quack-Quack a[0] = new Cow(); a[1] = new Dog(); a[2] = new Duck(); for(int i=0; i< a.length; i++) a[i].makesound(); public class Cow extends Animal System.out.println("Moo-Moo"); public class Dog extends Animal System.out.println( Wuf-Wuf"); public class Duck extends Animal System.out.println( Quack-Quack"); public abstract class Animal abstract void makesound(); public void move() System.out.println( walk ); Polymorphism via Inheritance Consider the following class hierarchy: StaffMember public class Cow extends Animal System.out.println("Moo-Moo"); public class Dog extends Animal System.out.println( Wuf-Wuf"); Volunteer Employee public class Duck extends Animal System.out.println( Quack-Quack"); public void move() Override the move System.out.println( fly ); method defined in the Animal class. 2004 Pearson Addison-Wesley. All rights reserved Executive Hourly 7

Employee Class Hierarchy Polymorphism via Inheritance Now let's look at an example that pays a set of diverse employees using a polymorphic method See Firm.java (page 486) See Staff.java (page 487) See StaffMember.java (page 489) See Volunteer.java (page 491) See Employee.java (page 492) See Executive.java (page 493) See Hourly.java (page 494) THE END 8