Object-Oriented Programming

Similar documents
Inheritance & Polymorphism. Object-Oriented Programming

Object-Oriented Programming

Inheritance, polymorphism, interfaces

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

First IS-A Relationship: Inheritance

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

More Relationships Between Classes

Object-Oriented Programming More Inheritance

Software Development (cs2500)

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

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

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

CSA 1019 Imperative and OO Programming

Example: Count of Points

Chapter 14 Abstract Classes and Interfaces

CST242 Object-Oriented Programming Page 1

Create a Java project named week10

Java Object Oriented Design. CSC207 Fall 2014

C09: Interface and Abstract Class and Method

Java Fundamentals (II)

Inheritance, Polymorphism, and Interfaces

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

CH. 2 OBJECT-ORIENTED PROGRAMMING

Reusing Classes. Hendrik Speleers

CS-202 Introduction to Object Oriented Programming

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

Exercise: Singleton 1

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

Instance Members and Static Members

Binghamton University. CS-140 Fall Chapter 9. Inheritance

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

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

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

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

Inheritance and Polymorphism

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Upcasting. Taking an object reference and treating it as a reference to its base type is called upcasting.

Inheritance in Ruby. You are familiar with the idea of inheritance and how to use this in programming.

ITI Introduction to Computing II

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

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

Inheritance & Polymorphism

C18a: Abstract Class and Method

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

ITI Introduction to Computing II

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

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

Inheritance (P1 2006/2007)

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

OVERRIDING. 7/11/2015 Budditha Hettige 82

CS111: PROGRAMMING LANGUAGE II

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

COP 3330 Final Exam Review

Programming in the Large II: Objects and Classes (Part 2)

Inheritance and Polymorphism. CS180 Fall 2007

CHAPTER 10 INHERITANCE

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

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

What is Inheritance?

OBJECT ORİENTATİON ENCAPSULATİON

INHERITANCE Mrs. K.M. Sanghavi

Intro to Computer Science 2. Inheritance

Principles of Software Construction: Objects, Design, and Concurrency

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

Object-Oriented Programming

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

Chapter 9 - Object-Oriented Programming: Polymorphism

More on Java. Object-Oriented Programming

Polymorphism and Interfaces. CGS 3416 Spring 2018

Introduction to Inheritance

Example: Count of Points

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012

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

Java Session. Day 2. Reference: Head First Java

8359 Object-oriented Programming with Java, Part 2. Stephen Pipes IBM Hursley Park Labs, United Kingdom

CSE 8B Programming Assignments Spring Programming: You will have 5 files all should be located in a dir. named PA3:

COMP 110/L Lecture 19. Kyle Dewey

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

EKT472: Object Oriented Programming. Overloading and Overriding Method

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

Polymorphism. Agenda

CSE 143 Lecture 20. Circle

CS 251 Intermediate Programming Inheritance

Chapter 6 Introduction to Defining Classes

8. Polymorphism and Inheritance

Object-Oriented ProgrammingInheritance & Polymorphism

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Polymorphism. Arizona State University 1

Transcription:

Abstract classes Object-Oriented Programming

Outline Abstract classes Abstract methods Design pattern: Template method Dynamic & static binding Upcasting & Downcasting Readings: HFJ: Ch. 8. GT: Ch. 8. Đại học Công nghệ - ĐHQG HN Abstract classes 2

Our previous design Dog d = new Dog(); Cat c = new Cat(); Fine. But Animal anim = new Animal(); What does an Animal look like? Đại học Công nghệ - ĐHQG HN Abstract classes 3

What does an Animal look like? What does a new Animal() object look like? What are the values of its instance variables? What should makenoise(), eat(), and roam() do? Do we ever need an Animal object? Đại học Công nghệ - ĐHQG HN Abstract classes 4

What does a Shape look like? What does a generic Shape object look like? How to draw() it? Do we ever need a Shape object? Shape - x, y + draw() + erase() Point + draw() + erase() Circle - radius + draw() + erase() Rectangle - width - height + draw() + erase() Đại học Công nghệ - ĐHQG HN Abstract classes 5

Abstract classes Some classes just should not be instantiated! We want Circle and Triangle objects, but no Shape objects. We want Dogs and Cats, but no Animal objects Make those generic classes abstract classes abstract class Animal {... The compiler will guarantee that no instances of abstract classes are created. But object references of abstract class types are allowed. Animal a = new Animal(); // Error!!! Animal anim = new Dog(); // no error. Đại học Công nghệ - ĐHQG HN Abstract classes 6

abstract public class Animal { public void eat() {... This is OK. You can always assign a subclass object to a super class reference, ----------------------------------------------- even if the superclass is abstract. public class MakeAnimal { public void go() { Animal a; class Animal is marked abstract, a = new Hippo(); so the compiler will NOT let you do create an instance of Animal. a = new Animal(); a.eat(); % javac MakeAnimal.java MakeAnimal.java:5: Animal is abstract; cannot be instantiated a = new Animal(); ^ 1 error Đại học Công nghệ - ĐHQG HN Abstract classes 7

Abstract vs. Concrete A class that is not abstract is called a concrete class How do we know when a class should be abstract? Đại học Công nghệ - ĐHQG HN Abstract classes 8

Abstract vs. Concrete mobile phone smart phone iphone iphone 4 iphone 4S Đại học Công nghệ - ĐHQG HN Abstract classes 9

Abstract methods How do we implement? Animal.makeNoise(), eat() We can't think of a generic implementation that is useful public void makenoise() { System.out.print("Hmm"); So, we mark those methods abstract. Abstract methods has no body. abstract public class Animal { public abstract void makenoise();... No method body! End it with a semicolon. Đại học Công nghệ - ĐHQG HN Abstract classes 10

Abstract methods If you declared a method abstract, you must mark the class abstract, as well. You can't have a concrete class with an abstract method. An abstract class means that it must be extended. An abstract method means that it must be overriden. A concrete subclass must have all the inherited abstract methods implemented. Đại học Công nghệ - ĐHQG HN Abstract classes 11

abstract public class Shape { protected int x, y; Shape(int _x, int _y) { x = _x; y = _y; abstract public void draw(); abstract public void erase(); public void moveto(int _x, int _y) { erase(); x = _x; public class Circle extends Shape { y = _y; draw(); private int radius; public Circle(int _x, int _y, int _r) { super(_x, _y); radius = _r; public void draw() { System.out.println("Draw circle at "+x+","+y); public void erase() { System.out.println("Erase circle at "+x+","+y); Đại học Công nghệ - ĐHQG HN Abstract classes 12

Design pattern: Template method abstract class Shape { protected int x, y; public void moveto(int x1, int y1) { erase(); x = x1; y = y1; draw(); abstract public void erase(); abstract public void draw(); Đại học Công nghệ - ĐHQG HN Abstract classes 13

Account example You need to store information for bank accounts: current balance, and the total number of transactions for each account. The goal for the problem is to avoid duplicating code between the three types of account. An account needs to respond to the following messages: constructor(initialbalance) deposit(amount) withdraw(amount) endmonth(): Apply the end-of-month charge, print out a summary, zero the transaction count. The end-of-month charge is calculated depending on types of Accounts Normal : Fixed $5.0 fee at the end of the month Nickle n Dime: $1.00 fee for each withdrawal charged at the end of the month Gambler: With probability 0.49 there is no fee and no deduction to the balance With probability 0.51 the fee is twice the amount withdrawn Đại học Công nghệ - ĐHQG HN Abstract classes 14

Class design diagram Account *balance *transactions -deposit -withdraw -endmonth -endmonthcharge (abstract) Fee -endmonthcharge NickleNDime *withdrawcount -withdraw -endmonthcharge Gambler -withdraw -endmonthcharge Đại học Công nghệ - ĐHQG HN Abstract classes 15

public class AnimalList { private Animal[] animals = new Animal[5]; private int nextindex = 0; public void add(animal a) { if (nextindex < animals.length) { animals[nextindex] = a; System.out.print("Animal added at " + nextindex); nextindex++; public class AnimalTestDrive { public static void main(string [] args) { AnimalList list = new AnimalList(); Dog d = new Dog(); Cat c = new Cat(); list.add(d); list.add(c); Đại học Công nghệ - ĐHQG HN Abstract classes 16

public class AnimalList { private Animal[] animals = new Animal[5]; private int nextindex = 0; public Animal get(int index) { return animals[index]; public void add(animal a) { if public (nextindex class < DogTestDrive animals.length) { { animals[nextindex] public static void = a; main(string [] args) { System.out.print("Animal AnimalList list = new added AnimalList(); at " + nextindex); nextindex++; Dog d = new Dog(); list.add(d); d = list.get(0); // Error! d.chasecats(); The compiler doesn't know that list.get() refers to a Dog object! AnimalList Animal[] animals int nextindex add(animal a) get(int index) % javac DogTestDrive.java DogTestDrive.java:6: incompatible types found : Animal required: Dog d = list.get(0); ^ Đại học Công nghệ - ĐHQG HN Abstract classes 17

public class AnimalList { private Animal[] animals = new Animal[5]; private int nextindex = 0; public Animal get(int index) { return animals[index]; public void add(animal a) { if public (nextindex class < DogTestDrive animals.length) { { animals[nextindex] public static void = a; main(string [] args) { System.out.print("Animal AnimalList list = new added AnimalList(); at " + nextindex); nextindex++; Dog d = new Dog(); list.add(d); Animal a = list.get(0); // We know the object is a Dog! a.chasecats(); // Error! Animal doesn't have chasecats()! The compiler doesn't know that a refers to a Dog object! Đại học Công nghệ - ĐHQG HN Abstract classes 18

Subclass object & the inherited part The Object remote control has fewer buttons! Đại học Công nghệ - ĐHQG HN Abstract classes 19

The rules Which method version get invoked depends on the object type. Whether a method call is allowed depends on the reference type what buttons the remote control has. Object o = new Cow(); o.tostring(); o.moo(); Cow's tostring() is invoked because o is now refering to an Cow object. o.tostring() is allowed because Object has tostring(). But o.moo() is not allowed because Object does not has moo() Đại học Công nghệ - ĐHQG HN Abstract classes 20

Dynamic & static binding Method binding: connect a method call to a method body Static/early binding: performed by compiler/linker before the program is run. The only option of procedural languages. Dynamic/late binding: performed during run-time Java uses late binding, except for static, final, and private methods. private methods are implicitly final. Đại học Công nghệ - ĐHQG HN Abstract classes 21

Casting How to make the Cow act like a Cow, again? Use an explicit cast: Object o = new Cow(); o.tostring(); o.moo(); // Error! Object o = new Cow(); o.tostring(); Cow c = (Cow) o; c.moo(); // no error ( ): cast operator, casting to the type Cow Explicit cast is not always possible: Object o = new Cat(); Cow c = (Cow) o; // no compile-time error c.moo(); // run-time error Đại học Công nghệ - ĐHQG HN Abstract classes 22

Upcasting & down casting Upcasting: casting up the diagram. Downcasting: casting down the diagram. Object o = new Cow(); implicit casting from Cow to Object Object Cow + moo() Object o;... Cow c = (Cow) o; explicit casting from Object to Cow Đại học Công nghệ - ĐHQG HN Abstract classes 23

Abstract super class As a super class A common superclass for several subclasses Factor up common behavior Define the methods all the subclasses respond to As an abstract class Force concrete subclasses to override methods that are declared as abstract in the super class Circle, Triangle must implement their own draw() and erase() Forbid creation of instants of the abstract superclass Shape objects are not allowed Đại học Công nghệ - ĐHQG HN Abstract classes 24