Object-Oriented Programming: Polymorphism



Similar documents
SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

CS193j, Stanford Handout #10 OOP 3

Using Inheritance and Polymorphism

Java Interview Questions and Answers

Part I. Multiple Choice Questions (2 points each):

History OOP languages Year Language 1967 Simula Smalltalk

Java CPD (I) Frans Coenen Department of Computer Science

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Chapter 13 - Inheritance

AP Computer Science Java Subset

Java Programming Language

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Fundamentals of Java Programming

Abstract Class & Java Interface

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Introduction: Abstract Data Types and Java Review

D06 PROGRAMMING with JAVA

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

ATM Case Study OBJECTIVES Pearson Education, Inc. All rights reserved Pearson Education, Inc. All rights reserved.

LAB4 Making Classes and Objects

Glossary of Object Oriented Terms

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Checking Access to Protected Members in the Java Virtual Machine

Java (12 Weeks) Introduction to Java Programming Language

Advanced Data Structures

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

11 November

java Features Version April 19, 2013 by Thorsten Kracht

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Construction of classes with classes

Agile Software Development

CS170 Lab 11 Abstract Data Types & Objects

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

How To Design Software

Object-Oriented Programming in Java

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Inheritance, overloading and overriding

Building Java Programs

Object-Oriented Programming in Java

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Introducing Variance into the Java Programming Language DRAFT

Introduction to Object-Oriented Programming

CS 111 Classes I 1. Software Organization View to this point:

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

Habanero Extreme Scale Software Research Project

Programmation 2. Introduction à la programmation Java

Object-Oriented Programming Lecture 2: Classes and Objects

Design Patterns in Java

CSE 1020 Introduction to Computer Science I A sample nal exam

More on Objects and Classes

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Getting Started with the Internet Communications Engine

Abstract Classes. Suppose we want write a program that manipulates various types of bank accounts. An Account typically has following features;

Java Application Developer Certificate Program Competencies

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Description of Class Mutation Mutation Operators for Java

ICOM 4015: Advanced Programming

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Classes and Objects. Agenda. Quiz 7/1/2008. The Background of the Object-Oriented Approach. Class. Object. Package and import

Chapter 1 Fundamentals of Java Programming

Chapter 2 Introduction to Java programming

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

CIS 190: C/C++ Programming. Polymorphism

JAVA - OBJECT & CLASSES

The Interface Concept

Lecture 9. Semantic Analysis Scoping and Symbol Table

5. Advanced Object-Oriented Programming Language-Oriented Programming

Introduction to Programming

UML Class Diagrams (1.8.7) 9/2/2009

Computing Concepts with Java Essentials

Introduction to Java

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Checking Access to Protected Members in the Java Virtual Machine

Automatic generation of fully-executable code from the Domain tier of UML diagrams

Install Java Development Kit (JDK) 1.8

Introduction to Object-Oriented Programming

Object Oriented Design

J a v a Quiz (Unit 3, Test 0 Practice)

The UML Class Diagram

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

The first program: Little Crab

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Structural Design Patterns Used in Data Structures Implementation

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Johannes Sametinger. C. Doppler Laboratory for Software Engineering Johannes Kepler University of Linz A-4040 Linz, Austria

Transcription:

1 10 Object-Oriented Programming: Polymorphism 10.3 Demonstrating Polymorphic Behavior 10.4 Abstract Classes and Methods 10.5 Case Study: Payroll System Using Polymorphism 10.6 final Methods and Classes 10.7 Case Study: Creating and Using Interfaces 2 1

10.3 Demonstrating Polymorphic Behavior 3 A superclass reference can be aimed at a subclass object (i.e., 調 用 不 同 子 類 別 的 method) This is possible because a subclass object is a superclass object as well When invoking a method from that reference, the type of the actual referenced object, not the type of the reference, determines which method is called The same method name and signature can cause different actions to occur, depending on the type of object on which the method is invoked (to write a more general program) Concept of Polymorphism 4 class Vehicle public void start() System.out.println("Starting..."); class Jet extends Vehicle public void start() System.out.println("2nd Starting..."); public void zoom() System.out.println("zooming..."); Vehicle Jet Is-A 2

5 class App232 public static void main(string[] args) Vehicle j = new Jet(); j.start(); // aims to method of subclass flexibility //j.zoom(); error: cann't find symbol > 2nd Starting... Exercise 6 設 計 方 法 display(obj), 其 參 數 obj 可 以 是 Whierlybird, Aircraft, or Jet 類 別 的 物 件, 並 顯 示 物 件 obj 所 有 field 的 值 Alternative 1. entirely 3 versions of display() Alternative 2. only 1 versions of display() Is-A Vehicle Whirlybird a1 a2 Aircraft b1 Jet c1 c2 c3 3

2nd Polymorphism Example Fig 10.1 7 CommissionEmploy3 See Fig 9.12, 9.13 + tostring(): double BasePlusCommissionEmploy4 - basesalary + tostring(): double 10.4 Abstract Classes and Methods 8 Abstract classes Used only as abstract superclasses for concrete subclasses and to declare reference variables Keyword abstract (see Fig. 10-4) Use to declare a class abstract Also use to declare a method abstract Abstract classes normally contain one or more abstract methods All concrete subclasses must override all inherited abstract methods 4

9 Extract common members -firstname - lastname - securitynumber Differ in earning() and tostring() - weeklysalary - grosssales - commissionrate - wage - hours For Fig 10.4 ~ 10.8 - basesalary Fig. 10.2 Employee hierarchy UML class diagram. Exercise 1 10 下 面 的 程 式 中, 在 抽 象 類 別 CShape 裡 已 定 義 好 一 個 show(), 以 及 一 個 abstract method 請 在 CWin 類 別 裡 撰 寫 area() method 的 定 義, 使 得 我 們 可 以 利 用 CWin 類 別 來 顯 示 物 件 的 width height 與 面 積 例 如, 在 第 24 行 建 立 CWin 類 別 的 物 件 win 後, 便 可 利 用 它 來 執 行 第 25 行 的 呼 叫 01 // hw11_2, 抽 象 類 別 02 abstract class CShape 03 04 protected int width; 05 protected int height; 06 07 public void show() 08 09 System.out.println("width="+width); 10 System.out.println("height="+height); 11 System.out.println("area="+area()); 12 13 public abstract int area(); // 計 算 面 積 14 5

11 15 class CWin extends CShape 16 17 // 請 完 成 這 個 部 分 的 程 式 碼 18 19 20 public class hw11_2 21 22 public static void main(string args[]) 23 24 CWin win=new CWin(5,7); // 建 立 CWin 類 別 的 物 件 25 win.show(); 26 27 10.5 Case Study: Payroll System Using Polymorphism 12 Fig 10.9 6

13 Dynamic binding Calls to overridden methods are resolved at execution time, based on the type of object referenced Downcasting Convert a reference to a superclass to a reference to a subclass Allowed only if the object has an is-a relationship with the subclass The same method name and signature can cause different actions to occur, depending on the type of object on which the method is invoked (to write a more general program) Summary of the Allowed Assignments Superclass and subclass assignment rules Assigning a superclass reference (i.e., object instance) to a superclass variable (i.e., object reference) is straightforward Assigning a subclass reference to a subclass variable is straightforward Assigning a subclass reference to a superclass variable is safe because of the is-a relationship Referring to subclass-only members through superclass variables is a compilation error Assigning a superclass reference to a subclass variable is a compilation error Downcasting can get around this error 14 7

10.6 final Methods and Classes 15 final methods Cannot be overridden in a subclass private and static methods are implicitly final final methods are resolved at compile time, this is known as static binding final classes Cannot be extended by a subclass All methods in a final class are implicitly final Final (1) 16 class animal final void breathe() System.out.println("Breathing..."); class fish extends animal public void breathe() System.out.println("Bubbling..."); 8

Final (2) 17 final class animal public void breathe() System.out.println("Breathing..."); class fish extends animal public void breathe() System.out.println("Bubbling..."); Final (3) 18 class app242 public static void main(string[] args) final int a = 5; a = 6; > 1 error Cannot assign a value to final variable a 9

10.7 Case Study: Creating and Using Interfaces 19 Interfaces Keyword interface Contains only constants and abstract methods All fields are implicitly public, static and final All methods are implicitly public abstract methods Typically used when disparate ( 不 同 的 ) classes need to share common methods and constants Interface (1) 20 import java.io.*; interface Vehicle // No method-definitions public void startengine(); public void stopengine(); interface Asset // No method-definitions public int initialcost(); public int currentcost(); 在 C++ 中 可 以 使 用 多 重 繼 承, 但 在 Java 中 只 能 單 一 繼 承, 也 就 是 一 次 只 能 擴 充 一 個 類 別,Java 使 用 interface 來 達 到 多 重 繼 承 的 目 的 10

extends class-a implements class-b 21 public class int01 implements Vehicle, Asset public void startengine() // no overriding among interfaces System.out.println("aaa"); public void stopengine() System.out.println("bbb"); public int initialcost() return 2; public int currentcost() return 3; 22 public static void main(string args[]) int01 a = new int01(); a.startengine(); a.stopengine(); System.out.println(a.initialCost()); System.out.println(a.currentCost()); aaa bbb 2 3 11

Interface (2) 23 interface ishape final double PI=3.14; abstract void setcolor(string str); interface ishape2d extends ishape abstract void area(); 24 class CCircle implements ishape2d double radius; String color; public CCircle(double r) radius=r; public void setcolor(string str) color=str; System.out.println("color="+color); public void area() System.out.println("area="+PI*radius*radius); 12

25 public class app11_7 public static void main(string args[]) CCircle cir; cir=new CCircle(2.0); cir.setcolor("blue"); cir.area(); Exercise 2 26 下 面 的 程 式 碼 是 修 改 自 習 題 1, 其 中 把 抽 象 類 別 CShape 改 以 介 面 來 宣 告 請 在 CWin 類 別 裡 撰 寫 show() 及 area() method 的 定 義, 使 得 我 們 可 以 利 用 CWin 類 別 來 顯 示 物 件 的 width height 與 面 積 01 // hw11_5, 介 面 實 作 02 interface ishape 03 04 public void show(); 05 public int area(); // 計 算 面 積 06 13

27 07 class CWin implements ishape 08 09 protected int width; 10 protected int height; 11 12 // 請 完 成 這 個 部 分 的 程 式 碼 13 14 15 public class hw11_5 16 17 public static void main(string args[]) 18 19 CWin win=new CWin(5,7); // 建 立 CWin 類 別 的 物 件 20 win.show(); 21 22 Exercise 3 28 下 面 的 程 式 碼 是 修 改 自 習 題 3, 其 中 增 加 了 一 個 icolor 介 面 icolor 介 面 裡 定 義 了 1 個 method: public void showcolor();// 顯 示 顏 色 請 在 CWin 類 別 裡 撰 寫 showcolor() method 的 定 義, 使 得 我 們 可 以 利 用 CWin 類 別 來 顯 示 物 件 的 顏 色 width height 與 面 積 01 // hw11_9, 多 重 繼 承 的 練 習 02 interface ishape 03 04 public void show(); 05 public int area(); 06 07 interface icolor 08 09 public void showcolor(); 10 14

29 11 class CWin implements ishape,icolor 12 13 // 請 完 成 這 個 部 分 的 程 式 碼 14 15 16 public class hw11_9 17 18 public static void main(string args[]) 19 20 CWin win=new CWin(5,7,"Green"); 21 win.show(); 22 23 30 Fig 10.11 10.15 realization 發 票 15

10.7.7 Declaring Constants with Interfaces 31 Interfaces can be used to declare constants used in many class declarations These constants are implicitly public, static and final Using a static import declaration allows clients to use these constants with just their names A reference to a subclass object can be assigned to an interface variable if the superclass implements that interface 16