CS 211: Inheritance. Chris Kauffman. Week 5-2

Similar documents
CS 211: Basic Inheritance

The class Object. Lecture CS1122 Summer 2008

Inheritance (Part 5) Odds and ends

CSCI 1103: File I/O, Scanner, PrintWriter

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.

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

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

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Rules and syntax for inheritance. The boring stuff

COE318 Lecture Notes Week 8 (Oct 24, 2011)

Binghamton University. CS-140 Fall Dynamic Types

AP CS Unit 6: Inheritance Notes

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

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

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

Building Java Programs. Inheritance and Polymorphism

Java Magistère BFA

CS 211: Existing Classes in the Java Library

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

CS 61B Data Structures and Programming Methodology. July 3, 2008 David Sun

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

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

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

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

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

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

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

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

CS 211: Methods, Memory, Equality

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

CS 101 Fall 2005 Midterm 2 Name: ID:

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

CSCI 1103: File I/O, Scanner, PrintWriter

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

F I N A L E X A M I N A T I O N

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

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)

CLASS DESIGN. Objectives MODULE 4

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Introduction to Object-Oriented Programming

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

CSCI 2041: Object Systems

CS 211: Potpourri Enums, Packages, Unit Tests, Multi-dimensional Arrays Command Line Args

CIS 110: Introduction to computer programming

More about inheritance

Class, Variable, Constructor, Object, Method Questions

Administrivia. IBM Info Session Date: Wed,, Jan 13 Time: 5:30 7 pm Location: Wesbrook 100

CS 231 Data Structures and Algorithms, Fall 2016

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

Media Computation. Lecture 16.1, December 8, 2008 Steve Harrison

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Inheritance & Polymorphism

CSE 331 Spring 2018 Midterm

Java Fundamentals (II)

About this sample exam:

Lecture 5: Implementing Lists, Version 1

Programming Languages and Techniques (CIS120)

CSCI 1103: Introduction

Making New instances of Classes

Java Object Oriented Design. CSC207 Fall 2014

CSE 331 Software Design & Implementation

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

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

Super-Classes and sub-classes

Java and C# in Depth

Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name:

CSE 331 Software Design & Implementation

Expected properties of equality

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

Logistics. Final Exam on Friday at 3pm in CHEM 102

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

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

Create a Java project named week10

Inheritance (Part 2) Notes Chapter 6

Operators and Expressions

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

AP CS Unit 6: Inheritance Exercises

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

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

CSCI 1103: Input with TextIO

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Final Exam Practice. Partial credit will be awarded.

Administrivia. CPSC Winter 2008 Term 1. Department of Computer Science Undergraduate Events

What is Inheritance?

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

More on Java. Object-Oriented Programming

Inheritance (Outsource: )

CS/ENGRD 2110 SPRING 2018

Creating an Immutable Class. Based on slides by Prof. Burton Ma

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

More Relationships Between Classes

Distributed Systems Recitation 1. Tamim Jabban

You have seen abstractions in many places, lets consider them from the ground up.

CS 302 Week 14. Jim Williams, PhD

First IS-A Relationship: Inheritance

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

C12a: The Object Superclass and Selected Methods

CSCI 1103: Object-Oriented Objects

Transcription:

CS 211: Inheritance Chris Kauffman Week 5-2

Logistics Goals Today Dynamic Dispatch Inheritance and Overrides Reminder: Career Fair 11:00 a.m.- 4:00 p.m. Dewberry Hall Wed 2/18: Science/Tech Thu 2/19: Business/Non-tech Reading: Inheritance Building Java Programs Ch 9 Lab Manual Ch 7 Lab 05: Exercise Inheriting from PrintWriter

Equality Gets Trickier What is printed on the right based on equals() definitions? public class Coord { public boolean equals(coord c){ return this.row==c.row && this.col==c.col; public class Coord3D extends Coord{ public boolean equals(coord3d other){ return this.row == other.row && this.col == other.col && this.height == other.height; Coord a = new Coord(1,2); Coord b = new Coord(10,12); Coord3D c = new Coord3D(1,2,3); Coord3D d = new Coord3D(10,12,14); System.out.println( a.equals(b) ); System.out.println( a.equals(c) ); System.out.println( a.equals(d) ); System.out.println(); System.out.println( b.equals(c) ); System.out.println( b.equals(d) ); System.out.println(); System.out.println( c.equals(d) ); System.out.println(); String s = "(1,2)"; System.out.println( s.equals(a) ); System.out.println( a.equals(s) );

Everyone has equals() and tostring() package java.lang; public class Object Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. public String tostring() Returns a string representation of the object. public boolean equals(object obj) Indicates whether some other object is "equal to" this one. int a[] = {1,2,3, b[] = {1,2,3; System.out.println( a.equals(b) ); //??

Checking type at run time: instanceof X instanceof Y A keyword/syntax construct true if X has Y as an ancestor - X is a Y Mascot is a Duck, Duck is a Animal, Animal is a Object false otherwise

Casting: Trust me, javac Object o = new Coord(1,2); System.out.println(o.row); Coord c = (Coord) o; System.out.println(c.row); // Compile error // Trust me, it s a Coord // Voila! What can go wrong with casting: (Coord) o Try it interactively: Object o = new String("hi"); Coord c = (Coord) o; What about the following... Object x = new Coord(1,2); Object y = new Coord(1,2); System.out.println( x.equals(y) );

The most common case of casting Compare current object like Coord to arbitrary other Objects Coord.equals(Object o) This works great now // Are coordinates equal public boolean equals(coord c){ return this.row==c.row && this.col==c.col; // Compare arbitrary object public boolean equals(object o){ if(o instanceof Coord){ Coord c = (Coord) o; return this.equals(c); else{ return false; Object x = new Coord(1,2); Object y = new Coord(1,2); System.out.println( x.equals(y) ); But what about... Object w = new Coord(1,2); Object z = new Coord3D(1,2,3); System.out.println( w.equals(z) ); System.out.println( z.equals(w) ); (Hint: damn... )

Dynamic Dispatch Suppose we have an animal Animal a =...; Methods: Single Dispatch a.dosomething() Call the method dosomething() with the most specific kind of thing a is as this Always done of method invocation There is runtime performance penalty No Dispatch on Arguments somefunction(a); Call method somefunction() with a treated as a plain Animal as the argument Type of a determined at compile time and appropriate method is chosen No runtime performance penalty SingleDispatch.java demonstrates this difference

Multiple Dispatch Incredibly useful in some programming problems as it simplifies code but not present in java: see the code in DoubleDispatch.java public static void meets(animal x, Animal y){ System.out.println("Nothing special"); public static void meets(snake x, Mouse y){ System.out.println("Snake eats mouse"); public static void main(string args[]){ Animal x = new Snake(); Animal y = new Mouse(); meet(x,y); // What do I print?

Extending Classes You Can t See Inside When writing programs Create whole new class hierarchy: Rare Extend someone else s class: Frequent PrintWriter and Extensions Lab will have you extending the java.io.printwriter class Can t see the source code (without searching for it) How do you extend it?

PrintWriter A class that allows printing to the screen or to a file PrintWriter out = new PrintWriter(new File("myfile.txt")); // PrintWriter out = new PrintWriter("myfile.txt"); // PrintWriter out = new PrintWriter(System.out); out.println("sweet foutput"); out.printf("an int: %d\na double %.1f\nA string: %s\n", 1, 2.5, "Three"); out.close(); // May close System.out (bad) Have a look at the PrintWriter Java Doc.

Exercise ScreamWriter It s bad form to SCREAM TEXT CONSTANTLY But some folks do it anyway Extend PrintWriter to ScreamWriter which screams output Welcome to DrJava. > ScreamWriter out = new ScreamWriter(System.out); > out.println("hello. How do you do?") HELLO. HOW DO YOU DO? > out.println("what s that? I can t hear you. Someone is shouting.") WHAT S THAT? I CAN T HEAR YOU. SOMEONE IS SHOUTING. > > import java.io.printwriter; > out instanceof PrintWriter true > out instanceof ScreamWriter true

ScreamWriter Strategy Extend PrintWriter public class ScreamWriter extends PrintWriter Create some constructors that allow ScreamWriters to be created. Will need to call parent class constructor. public ScreamWriter(OutputStream o) throws Exception public ScreamWriter(File f) throws Exception Override the PrintWriter methods println(string) and print(string) methods to behave differently. Will need to use the parent class versions too. public void println(string s) public void print(string s) // Print all caps // Print all caps Grind on this one a few minutes. Answer in today s code pack.