Building Java Programs. Inheritance and Polymorphism

Similar documents
CSE 143 Lecture 25. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides adapted from Marty Stepp

CSE 143 Lecture 21. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp

CSE 143 Lecture 22. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp

CSE 143 Lecture 22. The Object class; Polymorphism. read slides created by Marty Stepp and Ethan Apter

CSE 143 Lecture 12 Inheritance

Exceptions and Libraries

Inheritance. = way of forming new classes based on existing ones = way to share/reuse codebetween two or more classes

CSE 373. Objects in Collections: Object; equals; compareto; mutability. slides created by Marty Stepp

AP Computer Science. Interactions with superclass

INHERITANCE. Spring 2019

Super-Classes and sub-classes

Lecture 15: Inheritance II

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Building Java Programs

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

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

The class Object. Lecture CS1122 Summer 2008

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

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

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

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

CS-202 Introduction to Object Oriented Programming

Topic 31 - inheritance

1 Shyam sir JAVA Notes

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

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

CLASS DESIGN. Objectives MODULE 4

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Introduction to Object-Oriented Programming

COE318 Lecture Notes Week 8 (Oct 24, 2011)

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

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

CS260 Intro to Java & Android 03.Java Language Basics

6.Introducing Classes 9. Exceptions

Intro to Computer Science 2. Inheritance

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

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012)

Inheritance. The Java Platform Class Hierarchy

Abstract Classes and Interfaces

Input-Output and Exception Handling

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

COP 3330 Final Exam Review

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Introduction to Programming Using Java (98-388)

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

More On inheritance. What you can do in subclass regarding methods:

Expected properties of equality

CSE 331 Software Design & Implementation

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Introduction to Inheritance

BBM 102 Introduction to Programming II

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

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

Inheritance. Transitivity

CS 106B Lecture 27: Inheritance and Polymorphism in C++

CSE 331 Spring 2018 Midterm

The Java Type System (continued)

Methods Common to all Classes

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CSE 331 Software Design & Implementation

Sri Vidya College of Engineering & Technology Question Bank

Section: Inheritance Heck

Programming Languages and Techniques (CIS120)

Java Magistère BFA

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

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Check out Polymorphism from SVN. Object & Polymorphism

CSc 335 Inheritance Hell

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

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lecture 4. Types, Memory, Exceptions

Compaq Interview Questions And Answers

M257 Past Paper Oct 2008 Attempted Solution

Implementing Object Equivalence in Java Using the Template Method Design Pattern

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

AP CS Unit 6: Inheritance Notes

Subclasses, Superclasses, and Inheritance

CSCI 261 Computer Science II

JAVA MOCK TEST JAVA MOCK TEST II

File Processing. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

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

Java Review: Objects

Announcements. Equality. Lecture 10 Equality and Hashcode. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

AP Computer Science. Gridworld, inheritance

Java Object Oriented Design. CSC207 Fall 2014

CISC370: Inheritance

Inheritance -- Introduction

Programming Exercise 14: Inheritance and Polymorphism

Rules and syntax for inheritance. The boring stuff

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

Making New instances of Classes

What is Inheritance?

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?

Java Fundamentals (II)

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 9 Inheritance

Transcription:

Building Java Programs Inheritance and Polymorphism

Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many data sources: files on hard disk another computer on network web page input device (keyboard, mouse, etc.) represented by java.io classes InputStream OutputStream 3

Recall: inheritance inheritance: Forming new classes based on existing ones. a way to share/reuse code between two or more classes superclass: Parent class being extended. subclass: Child class that inherits behavior from superclass. gets a copy of every field and method from superclass is-a relationship: Each object of the subclass also "is a(n)" object of the superclass and can be treated as one. 4

Streams and inheritance input streams extend common superclass InputStream; output streams extend common superclass OutputStream guarantees that all sources of data have the same methods provides minimal ability to read/write one byte at a time 5

Inheritance syntax public class name extends superclass { public class Lawyer extends Employee {... override: To replace a superclass's method by writing a new version of that method in a subclass. public class Lawyer extends Employee { // overrides getsalary method in Employee class; // give Lawyers a $5K raise public double getsalary() { return 55000.00; 6

super keyword Subclasses can call inherited behavior with super super.method(parameters) super(parameters); public class Lawyer extends Employee { public Lawyer(int years) { super(years); // calls Employee constructor // give Lawyers a $5K raise public double getsalary() { double basesalary = super.getsalary(); return basesalary + 5000.00; Lawyers now always make $5K more than Employees. 7

I/O and exceptions exception: An object representing an error. checked exception: One that must be handled for the program to compile. Many I/O tasks throw exceptions. Why? When you perform I/O, you must either: also throw that exception yourself catch (handle) the exception 8

Throwing an exception public type name(params) throws type { throws clause: Keywords on a method's header that state that it may generate an exception. Example: public void processfile(string filename) throws FileNotFoundException { "I hereby announce that this method might throw an exception, and I accept the consequences if it happens." 9

Catching an exception try { statement(s); catch (type name) { code to handle the exception The try code executes. If the given exception occurs, the try block stops running; it jumps to the catch block and runs that. try { Scanner in = new Scanner(new File(filename)); System.out.println(input.nextLine()); catch (FileNotFoundException e) { System.out.println("File was not found."); 10

Exception inheritance Exceptions extend from a common superclass Exception 11

Dealing with an exception All exception objects have these methods: Method public String getmessage() public String tostring() getcause(), getstacktrace(), printstacktrace() Description text describing the error a stack trace of the line numbers where error occurred other methods Some reasonable ways to handle an exception: try again; re-prompt user; print a nice error message; quit the program; do nothing (!) 12

Inheritance and exceptions You can catch a general exception to handle any subclass: try { Scanner input = new Scanner(new File("foo")); System.out.println(input.nextLine()); catch (Exception e) { System.out.println("File was not found."); Similarly, you can state that a method throws any exception: public void foo() throws Exception {... Are there any disadvantages of doing so? 13

The class Object The class Object forms the root of the overall inheritance tree of all Java classes. Every class is implicitly a subclass of Object The Object class defines several methods that become part of every class you write. For example: public String tostring() Returns a text representation of the object, usually so that it can be printed. 14

Object methods method protected Object clone() public boolean equals(object o) protected void finalize() public Class<?> getclass() public int hashcode() public String tostring() public void notify() public void notifyall() public void wait() public void wait(...) description creates a copy of the object returns whether two objects have the same state used for garbage collection info about the object's type a code suitable for putting this object into a hash collection text representation of object methods related to concurrency and locking (take a data structures course!) 15

Using the Object class You can store any object in a variable of type Object. Object o1 = new Point(5, -3); Object o2 = "hello there"; You can write methods that accept an Object parameter. public void checknotnull(object o) { if (o!= null) { throw new IllegalArgumentException(); You can make arrays or collections of Objects. Object[] a = new Object[5]; a[0] = "hello"; a[1] = new Random(); List<Object> list = new ArrayList<Object>(); 16

Recall: comparing objects The == operator does not work well with objects. It compares references, not objects' state. It produces true only when you compare an object to itself. Point p1 = new Point(5, 3); Point p2 = new Point(5, 3); Point p3 = p2; // p1 == p2 is false; // p1 == p3 is false; // p2 == p3 is true // p1.equals(p2)? // p2.equals(p3)? p1 p2 p3 x 5 y 3... x 5 y 3... 17

Default equals method The Object class's equals implementation is very simple: public class Object {... public boolean equals(object o) { return this == o; However: When we have used equals with various objects, it didn't behave like ==. Why not? if (str1.equals(str2)) {... The Java API documentation for equals is elaborate. Why? 18

Implementing equals public boolean equals(object name) { statement(s) that return a boolean value ; The parameter to equals must be of type Object. Having an Object parameter means any object can be passed. If we don't know what type it is, how can we compare it? 19

Casting references Object o1 = new Point(5, -3); Object o2 = "hello there"; ((Point) o1).translate(6, 2); // ok int len = ((String) o2).length(); // ok Point p = (Point) o1; int x = p.getx(); // ok Casting references is different than casting primitives. Really casting an Object reference into a Point reference. Doesn't actually change the object that is referred to. Tells the compiler to assume that o1 refers to a Point object. 20

The instanceof keyword if (variable instanceof type) { statement(s); Asks if a variable refers to an object of a given type. Used as a boolean test. String s = "hello"; Point p = new Point(); expression s instanceof Point s instanceof String p instanceof Point p instanceof String p instanceof Object s instanceof Object null instanceof String result false true true false true true false null instanceof Object false 21

equals method for Points // Returns whether o refers to a Point object with // the same (x, y) coordinates as this Point. public boolean equals(object o) { if (o instanceof Point) { // o is a Point; cast and compare it Point other = (Point) o; return x == other.x && y == other.y; else { // o is not a Point; cannot be equal return false; 22

More about equals Equality is expected to be reflexive, symmetric, and transitive: a.equals(a) is true for every object a a.equals(b) b.equals(a) (a.equals(b) && b.equals(c)) a.equals(c) No non-null object is equal to null: a.equals(null) is false for every object a Two sets are equal if they contain the same elements: Set<String> set1 = new HashSet<String>(); Set<String> set2 = new TreeSet<String>(); for (String s : "hi how are you".split(" ")) { set1.add(s); set2.add(s); System.out.println(set1.equals(set2)); // true 23

Polymorphism 24

Polymorphism polymorphism: Ability for the same code to be used with different types of objects and behave differently with each. A variable or parameter of type T can refer to any subclass of T. Employee ed = new Lawyer(); Object otto = new Secretary(); When a method is called on ed, it behaves as a Lawyer. You can call any Employee methods on ed. You can call any Object methods on otto. You can not call any Lawyer-only methods on ed (e.g. sue). You can not call any Employee methods on otto (e.g. gethours). 25

Polymorphism examples You can use the object's extra functionality by casting. Employee ed = new Lawyer(); ed.getvacationdays(); ed.sue(); ((Lawyer) ed).sue(); // ok // compiler error // ok You can't cast an object into something that it is not. Object otto = new Secretary(); System.out.println(otto.toString()); // ok otto.getvacationdays(); // compiler error ((Employee) otto).getvacationdays(); // ok ((Lawyer) otto).sue(); // runtime error 26

"Polymorphism mystery" Figure out the output from all methods of these classes: public class Snow { public void method2() { System.out.println("Snow 2"); public void method3() { System.out.println("Snow 3"); public class Rain extends Snow { public void method1() { System.out.println("Rain 1"); public void method2() { System.out.println("Rain 2"); 27

"Polymorphism mystery" public class Sleet extends Snow { public void method2() { System.out.println("Sleet 2"); super.method2(); method3(); public void method3() { System.out.println("Sleet 3"); public class Fog extends Sleet { public void method1() { System.out.println("Fog 1"); public void method3() { System.out.println("Fog 3"); 28

Technique 1: diagram Diagram the classes from top (superclass) to bottom. Snow method2 method3 Rain method1 method2 (method3) Sleet method2 method3 Fog method1 (method2) method3 29

Technique 2: table method Snow Rain Sleet Fog method1 Rain 1 Fog 1 method2 Snow 2 Rain 2 Sleet 2 Snow 2 Sleet 2 Snow 2 method3() method3() method3 Snow 3 Snow 3 Sleet 3 Fog 3 Italic - inherited behavior Bold - dynamic method call 30

Mystery problem, no cast Snow var3 = new Rain(); var3.method2(); // What's the output? If the problem does not have any casting, then: 1. Look at the variable's type. If that type does not have the method: ERROR. 2. Execute the method, behaving like the object's type. (The variable type no longer matters in this step.) 31

Example 1 What is the output of the following call? Answer: Snow var1 = new Sleet(); var1.method2(); Sleet 2 Snow 2 Sleet 3 Rain method1 method2 (method3) variable Snow method2 method3 object Sleet method2 method3 Fog method1 (method2) method3 32

Example 2 What is the output of the following call? Answer: Snow var2 = new Rain(); var2.method1(); ERROR (because Snow does not have a method1) object Rain method1 method2 (method3) variable Snow method2 method3 Sleet method2 method3 Fog method1 (method2) method3 33

Mystery problem with cast Snow var2 = new Rain(); ((Sleet) var2).method2(); // What's the output? If the problem does have a type cast, then: 1. Look at the cast type. If that type does not have the method: ERROR. 2. Make sure the object's type is the cast type or is a subclass of the cast type. If not: ERROR. (No sideways casts!) 3. Execute the method, behaving like the object's type. (The variable / cast types no longer matter in this step.) 34

Example 3 What is the output of the following call? Answer: Snow var2 = new Rain(); ((Rain) var2).method1(); Rain 1 cast object Rain method1 method2 (method3) variable Snow method2 method3 Sleet method2 method3 Fog method1 (method2) method3 35

Example 4 What is the output of the following call? Answer: Snow var2 = new Rain(); ((Sleet) var2).method2(); ERROR (because the object's type, Rain, cannot be cast into Sleet) object Rain method1 method2 (method3) variable Snow method2 method3 Sleet method2 method3 cast Fog method1 (method2) method3 36