Object Oriented Software Design

Similar documents
Object Oriented Software Design

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

8. Interfaces & Inner Classes

Reusing Classes in Java. Java - Inheritance/Polymorphism/Interface. Inheritance. Simple Example of Composition. Composition.

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

COE318 Lecture Notes Week 10 (Nov 7, 2011)

BBM 102 Introduction to Programming II Spring Exceptions

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

6.Introducing Classes 9. Exceptions

Object Oriented Software Design

National University. Faculty of Computer Since and Technology Object Oriented Programming

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Internal Classes and Exceptions

BBM 102 Introduction to Programming II Spring 2017

Fundamentals of Object Oriented Programming

Object Oriented Programming

Polymorphism. OOAD 1998/99 Claudia Niederée, Joachim W. Schmidt Software Systems Institute

14. Exception Handling

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

7: Polymorphism. Interface & Implementation. Hands-on Java Seminar 2000 Bruce Eckel page 1. A Circle.

Exceptions. Examples of code which shows the syntax and all that

Exceptions Handling Errors using Exceptions

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Person class. A class can be derived from an existing class by using the form

Exception-Handling Overview

16-Dec-10. Consider the following method:

Person class. A class can be derived from an existing class by using the form

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

C16b: Exception Handling

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

9: Polymorphism. OOP = abstraction + inheritance + polymorphism

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Reusing Classes. Hendrik Speleers

Comp 249 Programming Methodology Chapter 9 Exception Handling

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Programming II (CS300)

Object Oriented Software Design II

Chapter 13 Exception Handling

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Exceptions - Example. Exceptions - Example

Object Oriented Software Design II

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Chapter 14. Exception Handling and Event Handling ISBN

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Exceptions. CSC207 Winter 2017

Data Structures. 02 Exception Handling

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Programming II (CS300)

CSCI 261 Computer Science II

Introduction to Programming Using Java (98-388)

Java Loose Ends. 11 December 2017 OSU CSE 1

Object Oriented Programming

EXCEPTION HANDLING. Summer 2018

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

Brief Summary of Java

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

More on Exception Handling


Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

More on Exception Handling

Data Structures. Subodh Kumar. Dept of Computer Sc. & Engg. IIT Delhi

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

Rules and syntax for inheritance. The boring stuff

Exceptions and Libraries

CS159. Nathan Sprague

Chapter 14. Exception Handling and Event Handling

Contents. I Introductory Examples. Topic 06 -Exception Handling

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Exceptions in Java

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

Object Oriented Software Design

COMP1008 Exceptions. Runtime Error

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

Lecture 19 Programming Exceptions CSE11 Fall 2013

COP 3330 Final Exam Review

Download link: Java Exception Handling

Exception Handling in Java

Object Oriented Software Design

ASSERTIONS AND LOGGING

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Sri Vidya College of Engineering & Technology Question Bank

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Design Patterns in C++

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

By: Abhishek Khare (SVIM - INDORE M.P)

Exception Handling. Chapter 9

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

School of Informatics, University of Edinburgh

Full file at Chapter 2 - Inheritance and Exception Handling

17. Handling Runtime Problems

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Transcription:

Object Oriented Software Design Polymorphism, Abstract Classes, Interfaces Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 1 / 38 Outline 1 Polymorphism 2 Abstract classes 3 Interfaces 4 Error handling with Exceptions G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 2 / 38

Using Inheritance Let s complete the example with the instruments Note Instrument instrument Player void play(note note) 1 1 Player(Instrument instrument) void tune(instrument instrument) void tuneall(instrument [] [music] instrument) Wind void play(note note) Stringed void play(note note) Percussion void play(note note) Woodwind Brass Violin void play(note note) void play(note note) void play(note note) G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 4 / 38 The Note class Let s start from the Note class music/note.java package music; public class Note { private String notename; private Note(String notename) { this.notename = notename; public String tostring() { return notename; public static final Note C = new Note("C"), C_SHARP = new Note("C Sharp"), D = new Note("D"), D_SHARP = new Note("D Sharp"), E = new Note("E"), F = new Note("F"); // Etc. ///:~ G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 5 / 38

The Note class The constructor is private This means that the user of the class cannot create any object of class Note Also, there is only method tostring() in the public interface The only thing that we can do is to use the public static members (C, D, E, etc.) that are all final (i.e. they are constant), and convert them to String. This the the standard way to create a set of constants with Java Similar to the enum in C/C++ G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 6 / 38 Class Instrument Instrument is the base class of our hierarchy music/instrument.java package music; public class Instrument { public void play(note n) { System.out.println("Instrument.play() " + n); public String what() { return "Instrument"; public void adjust() { G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 7 / 38

The Player class music/player.java package music; public class Player { String name; public Player(String name) { this.name = name; public String tostring() { return "Player : " + name; public void tune(instrument i) { i.play(note.c); public void tuneall(instrument[] e) { for(int i = 0; i < e.length; i++) tune(e[i]); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 8 / 38 The main MusicPlayer.java import com.bruceeckel.simpletest.*; import music.*; public class MusicPlayer { public static void main(string[] args) { Player player = new Player("Myself"); Instrument[] orchestra = { new Wind(), new Percussion(), new Stringed(), new Brass(), new Woodwind() ; player.tuneall(orchestra); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 9 / 38

What happens? The Player does not know about the existence of any of the Instrument classes it calls the play() method of Instrument and the play() method of the corresponding object is called When the Player.java is compiled, how can the compiler know which function to call? This mechanism is called dynamic binding At the time of compiling Player.java, the call is substituted by a simple code that looks into a table to understand with method to call We will see how the virtual table mechanism works when we will study C++ Right now, just remember that in Java you only have dynamic binding (and this causes some extra overhead in function calls) G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 10 / 38 Polymorphism This mechanism is also called polymorphism, and Java methods are said to be polymorphic Now, let s try to change the list of instruments Also, let s try to add a new Instrument (e.g. a Guitar) Which code needs to be changed? Not the Player class Not the Instrument class Only the MusicPlayer class which creates the Guitar object! We added a new behaviour with minimal changes The changes can even be less than that! We are not always so lucky Sometimes is not easy to minimise changes For example, in some cases we must know the object type! G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 11 / 38

Classes you cannot instantiate Let s continue with the Instrument example Does it make sense to create an object of a type Instrument? Does it make sense to call the play() method of the base class Instrument? No, actually there is not such a thing as an Instrument There are many types of Instrument This is where Abstract classes are useful We want to tell the language that it is not possible to create an instrument, and call its method Instrument represent an interface You do so by saying that a method is abstract, i.e. it has not implementation You also have to say that the class is abstract G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 13 / 38 Abstract Instrument Let s see the abstract version of our Instrument class: music2/instrument.java package music2; public abstract class Instrument { abstract public void play(note n); public String what() { return "Instrument"; public void adjust() { G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 14 / 38

Abstract Wind Of course, also Wind, Percussion and Stringed must be abstract: music2/wind.java package music2; public abstract class Wind extends Instrument { abstract public void play(note n); public String what() { return "Wind"; public void adjust() { music2/stringed.java package music2; public abstract class Stringed extends Instrument { abstract public void play(note n); public String what() { return "Stringed"; public void adjust() { G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 15 / 38 The main class Notice that this time we cannot create Wind and Percussion instruments: MusicPlayer2.java import com.bruceeckel.simpletest.*; import music2.*; public class MusicPlayer2 { public static void main(string[] args) { Player player = new Player("Myself"); Instrument[] orchestra = { new Woodwind(), new Violin(), new Brass(), new Woodwind() ; player.tuneall(orchestra); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 16 / 38

Completely abstract classes Instrument is now an abstract class It contains normal methods (with code), and one abstract method without code Sometimes it is useful to have only interfaces, i.e. classes where you do not provide any code at all In Java this is done with the interface keyword G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 18 / 38 Instrument interface Here is how Instrument is transformed into an interface: music3/instrument.java package music3; public interface Instrument { int I = 5; // this is static and final // all methods are public by default void play(note n); String what(); void adjust(); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 19 / 38

How to use Instrument With interfaces, you have to use the keyword implements instead of extends music3/wind.java package music3; public abstract class Wind implements Instrument { abstract public void play(note n); public String what() { return "Wind"; public void adjust() { music3/stringed.java package music3; public abstract class Stringed implements Instrument { abstract public void play(note n); public String what() { return "Stringed"; public void adjust() { G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 20 / 38 The main class Notice that you can declare a reference to an interface: MusicPlayer3.java import com.bruceeckel.simpletest.*; import music3.*; public class MusicPlayer3 { public static void main(string[] args) { Player player = new Player("Myself"); Instrument[] orchestra = { new Woodwind(), new Violin(), new Brass(), new Woodwind() ; player.tuneall(orchestra); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 21 / 38

Multiple interfaces A class can implement multiple interfaces It makes sense, because sometimes an object can be seen as two different types, depending on the context However, a class can extend only one other class The extend keyword must precede the implement keyword The implementation of the interface methods need not to be in the class itself It can be in the base class, or in the derived classes (in the latter case, the class becomes abstract) G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 22 / 38 Deriving from multiple interfaces Adventure.java interface CanFight { void fight(); interface CanSwim { void swim(); interface CanFly { void fly(); class ActionCharacter { public void fight() { class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { public void swim() { public void fly() { G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 23 / 38

UML class diagram CanFight CanFly CanSwim ActionCharacter fight() fly() swim() fight() Hero fly() swim() G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 24 / 38 Extending interfaces It is possible to extend and combine interfaces to obtain more complex ones To extend an interface with additional methods, you can use keyword extends, just as inheriting a derived class from a base class Unlike classes (where you can extend from one class only), you can extend an interface from multiple base interfaces public interface BInt1 { void fun1(); int g(); interface BInt2 { void fun2(); int h(); interface Der extends BInt1, BInt2 { void fun3(); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 25 / 38

Exceptions An exceptional condition is a run-time error that prevents the continuation of the function or scope the program is currently executing A normal error is something you can deal with in the current scope An exceptional condition is something you cannot do anything about at the current point of the program All you can do is to return from the method, signalling to the higher levels that the method failed to complete The typical way to handle this exceptional condition in C is to return an error code For example, many OS functions return a special error code to mean that the function failed to complete successfully Consider opening a file for reading. The user specifies the file name, but what happens if a file with that name cannot be found on the disk? The open() function cannot do anything about it; it returns a special error code, and the user has to check the return value to see if the function was successful G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 27 / 38 Exceptions in object oriented In procedural languages like C, handling exceptions is annoying For each function, you have to check the return value, and write some code to decide what to do Sometimes, the error cannot be addressed directly, so we have to propagate the error condition to the upper layers This adds a substantial amount of effort for the programmer, and makes the code less readable In Object Oriented languages, the idea is that you can handle the error where it is more appropriate through the concept of Exceptions An exception is just an object of a class (everything is an object) that the programmer can throw to signal the error condition The exception can then be caught where is more appropriate G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 28 / 38

Syntax First, let s use existing exceptions, provided by the Java library MyClass t;... // some code that works with t if(t == null) throw new NullPointerException(); In this example, we check if reference t points to an object If not, we throw an exception of type NullPointerException() Actually, the previous code is superfluous, since the same exception is thrown automatically whenever you use a null reference G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 29 / 38 Catching exceptions To be able to catch an exception, you must enclose the code in a try block try { // code that can throw an exception catch (Type1 exc1) { // code to handle exceptions of Type1 catch (Type2 exc2) { // code to handle exceptions of Type2 catch (Type3 exc3) { // code to handle exceptions of Type3 When an exception is thrown, The JVM looks for handler that catch the exception type If it does not find them, it goes up one scoping level, again searching for the right catch block If it does not find it, the program is terminated with an error An example:./examples/06.java-examples/simpleexceptiondemo.java G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 30 / 38

Constructors for Exceptions Exceptions are objects, they can be made as complex as we need FullConstructors.java class MyException extends Exception { public MyException() { public MyException(String msg) { super(msg); FullConstructors.java public static void g() throws MyException { System.out.println("Throwing MyException from g()"); throw new MyException("Originated in g()"); FullConstructors.java try { f(); catch(myexception e) { e.printstacktrace(); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 31 / 38 Throwable Your exception must derive from an existing library class called Exception, which extends class Throwable One of the methods of Throwable is printstacktrace() Here is the complete documentation for Exception http://download.oracle.com/javase/1.6.0/docs/api/java/lang/excepti G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 32 / 38

Exception specification If your method can throw an exception, you must specify this in the method declaration You must use the keyword throws followed by a comma-separate list of exceptions If you do not specify anything, it means your method does not throw anything In Java you cannot lie: if you throw an exception, you have to declare it in the method The exception is part of the method signature If a method of a base class specifies an exception list, all derived classes that override that method must specify the same exception list, else the compiler will complain Java uses checked exceptions (i.e. the check is done at compile time) C++ is more liberal in this respect G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 33 / 38 Exceptions hierarchy As you have already seen, exceptions can be organised into a hierarchy of base-derived classes When catching an exception, the normal type rules are applied If you catch Exception, you are actually catching any type of exceptions (as they all derive from class Exception). try {... catch (Exception e) { // this catches any type of exception The catch clauses are examined in the same order they are written It is convenient to put the above code at the end of the catch list, so that you first try to catch more specific exceptions, and then more generic ones. G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 34 / 38

Rethrowing an exception Sometimes, when an exception is thrown, it is useful to catch it to do some cleanup, and then throw it again so that the upper layers can handle it Therefore, inside a catch clause you can rethrow the same exception you have just caught catch(exception e) { System.err.println("An exception was thrown"); throw e; You can also throw a different exception, of course (that is always possible from anywhere) G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 35 / 38 Runtime exceptions There is an entire hierarchy of special exceptions, whose base class is RuntimeException These exceptions are automatically thrown by the JVM An example is NullPointerException Another one is ArrayIndexOutOfBoundsException It is not necessary to specify these exceptions in the exception specification list of a method (since these ones can originate from anywhere) We say that these exceptions are unchecked, because the compiler does not check from them G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 36 / 38

finally After the catch clauses, you can insert a finally clauses, a block of code that is always executed at the end the finally clause is executed when the exception is thrown, and when it is not thrown try { // The guarded region: Dangerous activities // that might throw A, B, or C catch(a a1) { // Handler for situation A catch(b b1) { // Handler for situation B catch(c c1) { // Handler for situation C finally { // Activities that happen every time An example:./examples/06.java-examples/alwaysfinally.java G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 37 / 38 Lost exceptions Unfortunately exceptions can get lost For example, when inside a finally clause, you call a method that can throw another exception: the second one will overwrite the first one../examples/06.java-examples/lostmessage.java G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 28, 2010 38 / 38