Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Similar documents
Computer Science 210: Data Structures

Inheritance. The Java Platform Class Hierarchy

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

Universiti Malaysia Perlis

Inheritance, part 2: Subclassing. COMP 401, Spring 2015 Lecture 8 2/3/2015

Data Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Data Structures Lecture 2

What is Inheritance?

Defensive Programming. Ric Glassey

Object-Oriented Programming

Tony Valderrama, SIPB IAP 2009

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Lecture 2: Java & Javadoc

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

CS260 Intro to Java & Android 03.Java Language Basics

Lesson: Classes and Objects

Java Programming Tutorial 1

Introduction and Review of Java: Part 2

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

Introduction to Java for C/C++ Programmers. Kevin Squire Department of Computer Science Naval Postgraduate School

CH. 2 OBJECT-ORIENTED PROGRAMMING

Chapter 5 Object-Oriented Programming

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

ITI Introduction to Computing II

Introduction to Programming Using Java (98-388)

Inheritance -- Introduction

ITI Introduction to Computing II

CS-202 Introduction to Object Oriented Programming

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

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

Object-Oriented Design. March 2005 Object Oriented Design 1

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Exercise: Singleton 1

Object-Oriented Programming

Polymorphism. return a.doublevalue() + b.doublevalue();

Java Primer 1: Types, Classes and Operators

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Example: Count of Points

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

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

Programming overview

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

Java Fundamentals (II)

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?

Operators and Expressions

Inheritance (Outsource: )

PROGRAMMING LANGUAGE 2

Java Object Oriented Design. CSC207 Fall 2014

Fundamentals of Object Oriented Programming

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

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

Inheritance and Polymorphism

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

First IS-A Relationship: Inheritance

Data Structures and Algorithms Design Goals Implementation Goals Design Principles Design Techniques. Version 03.s 2-1

Inheritance. Transitivity

Exception-Handling Overview

CO Java SE 8: Fundamentals

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

Internal Classes and Exceptions

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

6.Introducing Classes 9. Exceptions

Programming II (CS300)

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

More Relationships Between Classes

1 Shyam sir JAVA Notes

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 6 Introduction to Defining Classes

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance and Polymorphism

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

CS1150 Principles of Computer Science Objects and Classes

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

More on Objects in JAVA TM

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

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

What are Exceptions?

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

C++ Important Questions with Answers

Instance Members and Static Members

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

Chapter 4 Defining Classes I

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

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

Programming II (CS300)

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Introductory Programming Inheritance, sections

Example: Count of Points

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

Binghamton University. CS-140 Fall Dynamic Types

Programming II (CS300)

Practice for Chapter 11

Transcription:

COMP9024: Data Structures and Algorithms Week One: Java Programming Language (II) Hui Wu Session 1, 2014 http://www.cse.unsw.edu.au/~cs9024 Outline Inheritance and Polymorphism Interfaces and Abstract Classes Exceptions Casting and Generics 1 2 Object-Oriented Design Goals Object-Oriented Design Principles Robustness Capable of handling unexpected inputs that are not explicitly defined for an application. Adaptability Running a software with minimal changes on different hardware and operating system platforms. Reusability The same code is usable as a component of different systems in various applications. 3 Abstraction Distill a complicated system down to its most fundamental parts and describe these parts in a simple, precise language. Encapsulation Different components of a software system should not reveal the internal details of their respective implementations. Modularity Different components of a software system are divided into separated functional units. 4 Inheritance A technique that allows the design of general classes that can be specialized to more particular classes, with the specialized classes reusing the code from the general class. A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). What a Subclass Inherits from Its Superclass? A subclass inherits all the non-private members (fields, methods, and nested classes) from its superclass. Constructors are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass by using the operator super. 5 6 1

An Example of Inheritance (1/2) An Example of Inheritance (2/2) public class Bicycle { // the Bicycle class has three fields public int cadence; public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int startcadence, int startspeed, int startgear) { gear = startgear; cadence = startcadence; speed = startspeed; } // the Bicycle class has four methods public void setcadence(int newvalue) { cadence = newvalue; } public void setgear(int newvalue) { gear = newvalue; } public void applybrake(int decrement) { speed -= decrement; } public void speedup(int increment) { speed += increment; } } public class MountainBike extends Bicycle { // the MountainBike subclass adds one field public int seatheight; // the MountainBike subclass has one constructor public MountainBike(int startheight, int startcadence, int startspeed, int startgear) { super(startcadence, startspeed, startgear); seatheight = startheight; } // the MountainBike subclass adds one method public void setheight(int newvalue) { seatheight = newvalue; } } 7 8 What Can You Do in a Subclass? (1/2) The inherited fields can be used directly, just like any other fields. You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). You can declare new fields in the subclass that are not in the superclass. The inherited methods can be used directly as they are. What Can You Do in a Subclass? (2/2) You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. You can declare new methods in the subclass that are not in the superclass. You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. 9 10 Java Class Hierarchy Polymorphism Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object. 11 The ability of an object variable to take different forms. Overriding If a subclass and its superclass contain two instance methods with the same name, the instance method in the subclass overrides the one with the same name in its superclass. Hiding If a subclass and its superclass contain two class methods with the same name, the class method in the subclass hides the one with the same name in its superclass. Overloading A single class may contain multiple methods with the same name but different signatures. The signature of a method is a combination of its name and the type and number of arguments that are passed to it. 12 2

An Example of Overriding and Hiding (1/2) An Example of Overriding and Hiding (2/2) public class Animal { public static void testclassmethod() { System.out.println("The class method in Animal."); } public void testinstancemethod() { System.out.println("The instance method in Animal."); } } public class Cat extends Animal { public static void testclassmethod() { System.out.println("The class method in Cat."); } public void testinstancemethod() { System.out.println("The instance method in Cat."); } public static void main(string[] args) { Cat mycat = new Cat(); Animal myanimal = mycat; Animal.testClassMethod(); myanimal.testinstancemethod(); } } 13 14 Summary of Overriding and Hiding Dynamic Dispatch Defining a Method with the Same Signature as a Superclass's Method: Subclass Static Method Subclass Instance Method Superclass Static Method Hide Generates a compile-time error Superclass Instance Method Generates a compile-time error Override When a program invokes a certain method a() of a object o, the Java run-time environment checks if a() is defined in o s class T. If yes, then executes it; otherwise, checks if it is defined in T s superclass S. If yes, then executes it; otherwise, checks if it is defined in S s superclass P. This procedure is repeated until a definition of this method is found, or the topmost class is reached, in which case the Java runtime environment will generate a runtime error. 15 16 Accessing Superclass Members (1/2) Accessing Superclass Members (2/2) A subclass can access the members of its superclass via the keyword super. Consider the following example: public class Superclass { public void printmethod() { System.out.println("Printed in Superclass."); } } public class Subclass extends Superclass { public void printmethod() { //overrides printmethod in Superclass super.printmethod(); System.out.println("Printed in Subclass"); } public static void main(string[] args) { Subclass s = new Subclass(); s.printmethod(); } } 17 18 3

Subclass Constructors (1/2) Subclass Constructors (2/2) The syntax for calling a superclass constructor is super(); or super(parameter list); public MountainBike(int startheight, int startcadence, int startspeed, int startgear) { super(startcadence, startspeed, startgear); seatheight = startheight; } Invocation of a superclass constructor must be the first line in the subclass constructor. If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. 19 20 Referencing the Current Instance of a Class (1/2) Referencing the Current Instance of a class (2/2) Java provides the this operator to reference the current instance of of a class. public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; } } public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } } 21 public class Rectangle { private int x, y, width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; }... } 22 Exceptions (1/5) Exceptions (2/2) An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. Locating the exception handler: The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. 23 24 4

Exceptions (3/2) Exceptions (4/2) The call stack: Searching the call stack for the exception handler: The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates. 25 26 Exceptions (5/2) Three Types of Exceptions Searching the call stack for the exception handler: Checked exception These are exceptional conditions that a well-written application should anticipate and recover from. Error These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. Runtime exception These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. 27 28 The Throwable Class Error and Exception Classes Java platform provides numerous exception classes. All the classes are descendants of the Throwable class. Error class When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error. Exception class Most programs throw and catch objects that derive from the Exception class. An Exception indicates that a problem occurred, but it is not a serious system problem. 29 30 5

Throwing the Exceptions Specifying the Exceptions Syntax: throw somethrowableobject public Object pop() { Object obj; if (size == 0) { throw new EmptyStackException(); } obj = objectat(size - 1); setobjectat(size - 1, null); size--; return obj; } 31 When a method is declared, it is appropriate to specify the exceptions it might throw by using the keyword throws. public void getreadyforclass() throws ShoppingListTooSmallException, OutOfMoneyException { goshopping(); // I don't have to try or catch the exceptions // which goshopping() might throw because // getreadyforclass() will just pass these along. makecookiesforta(); } 32 Catching Exceptions (1/2) Catching Exceptions (1/2) Syntax: try main blcok of statement catch (exceptiontype1 variable) block 1 of statements catch (exceptiontype2 variable) block 2 of statements finally block n of statements Syntax: try main blcok of statements catch (exceptiontype1 variable1) block 1 of statements catch (exceptiontype2 variable2) block 2 of statements finally block n of statements 33 34 Catching Exceptions (2/2) Interface (1/7) public void writelist() { PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) out.println("value at: " + i + " = " + vector.elementat(i)); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught " + "ArrayIndexOutOfBoundsException: " + e.getmessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getmessage()); } finally { if (out!= null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } } } 35 A Java interface is a collection of methods declarartions without data and bodies. An interface cannot be instantiated it can only be implemented by a classe or extended by another interface. 36 6

Interface (2/7) Interface (3/7) Defining an interface is similar to creating a new class: /** Interface for objects that can be sold. */ public interface Sellable { /** description of the interface */ public String description(); /** list price in cents */ public int listprice(); /** lowest price in cents we will accept */ public int lowestprice(); } 37 To use an interface, you write a class that implements the interface: /** Class for photographs that can be sold */ public class Photograph implements Sellable { private String descript; // description of this photo private int price; // the price we are setting private boolean color; // true if photo is in color public Photograph(String desc, int p, boolean c) { // constructor descript = desc; price = p; color = c; } public String description() { return descript; } public int listprice() { return price; } public int lowestprice() { return price/2; } public boolean iscolor() { return color; } } 38 Interface (4/7) Interface (5/7) A class can implement multiple interfaces. Consider the following example: /** Interface for objects that can be transported. */ public interface Transportable { /** weight in grams */ public int weight(); /** whether the object is hazardous */ public boolean ishazardous(); } 39 The following class implements both Sellable and Transportable: /** Class for objects that can be sold, packed, and shipped. */ public class BoxedItem implements Sellable, Transportable { private String descript; // description of this item private int price; // list price in cents private int weight; // weight in grams private boolean haz; // true if object is hazardous private int height=0; // box height in centimeters 40 Interface (6/7) Interface (7/7) private int width=0; // box width in centimeters private int depth=0; // box depth in centimeters /** Constructor */ public BoxedItem(String desc, int p, int w, boolean h) { descript = desc; price = p; weight = w; haz = h; } public String description() { return descript; } public int listprice() { return price; } public int lowestprice() { return price/2; } public int weight() { return weight; } public boolean ishazardous() { return haz; } public int insuredvalue() { return price*2; } public void setbox(int h, int w, int d) { height = h; width = w; depth = d; } } 41 Although Java does not allow multiple inheritance for classes, it allows multiple inheritance for interfaces: public interface InsurableItem extends Transportable, Sellable { /** Returns insured Value in cents */ public int insuredvalue(); } public class BoxedItem2 implements InsurableItem { //... same code as class BoxedItem } 42 7

Abstract Classes Type Conversions (1/3) An abstract class is a class that contains empty method declarartions (that is, declarartions of methods without bodies) as well as concreate definitions of methods and/or instance variables. Like an interface, an abstract class may not be instantiated. A subclass must provide an implementation for the abstract methods of its superclass, unless it is itself abstract. Widenning conversions A widdening conversion occurs when a type T is converted into a wider type U. Common cases: T and U are class type and U is the superclass of T. T and U are interface types and U is the superinterface of T. T is a class that implements interface U. Narrowing conversions A narrowing conversion occurs when a type T is converted into a narrower type S. Common cases: T and S are class type and S is the subclass of T. T and S are interface types and S is the subinterface of T. T is an interface that implements class S. 43 44 Type Conversions (2/3) Type Conversions (3/3) Widenning conversions are automatically performed by Java to store the results of an expression into a variable. Therefore, no cast is needed. Integer i = new Integer(3); Number n = i; // widening conversion from Integer to Number In general narrowing conversions require an explicit cast. /** widening conversion from Integer to Number */ Number n = new Integer(2); /** narrowing conversion from Number to Integer */ Integer i = (Integer) n; Cast 45 46 The Operator instanceof Generics (1/4) Java provides an operator, instanceof, that allows us to test if an object variable is referring to an object of a certain class. Number n; Integer i; n = new Integer(3); if (n instanceof Integer) i = (Integer) n; // This is legal n = new Double(3.1415); if (n instanceof Integer) i = (Integer) n; // This will not be attempted Java provides a generic framework for using abstract types in a way that avoids many explicit casts. An generic type is a type that is not defined at compile time, but becomes fully specified at run time. The generic framework allows us to define a class in terms of a set of formal type parameters, which could be used, for example, to abstract the types of some internal variables of the class. When an object is instantiated, actual type parameters are passed to indicate the concrete types to be used. 47 48 8

Generics (2/4) Generics (3/4) public class Pair<K, V> { K key; V value; public void set(k k, V v) { key = k; value = v; } public K getkey() { return key; } public V getvalue() { return value; } public String tostring() { return "[" + getkey() + ", " + getvalue() + "]"; } public static void main (String[] args) { Pair<String,Integer> pair1 = new Pair<String,Integer>(); pair1.set(new String("height"), new Integer(36)); System.out.println(pair1); Pair<Student,Double> pair2 = new Pair<Student,Double>(); pair2.set(new Student("A5976","Sue",19), new Double(9.5)); System.out.println(pair2); } } 49 In the previous example, the actual parameter can be of any type. To restrict the type of an actual parameter, we can use an extends clause as shown below: public class PersonPairDirectoryGeneric<P extends Person> { /**... instance variables would go here... */ public PersonPairDirectoryGeneric() { /* default constructor goes here */ } public void insert (P person, P other) { /* insert code goes here */ } public P findother (P person) { return null; } // stub for find public void remove (P person, P other) { /* remove code goes here */ } } 50 Generics (4/4) References Type Parameter Naming Conventions: By convention, type parameter names are single, uppercase letters. The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value S,U,V etc. - 2nd, 3rd, 4th types 1. Chapter 2, Data Structures and Algorithms by Goodrich and Tamassia. 2. The Java TM Tutorials (http://java.sun.com/docs/books/tutorial/). 51 52 9