CS 61B Discussion 5: Inheritance II Fall 2014

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

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

Rules and syntax for inheritance. The boring stuff

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

Exception-Handling Overview

Array. Prepared By - Rifat Shahriyar

Full file at Chapter 2 - Inheritance and Exception Handling

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

What can go wrong in a Java program while running?

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

Sri Vidya College of Engineering & Technology Question Bank

CMSC 331 Second Midterm Exam

Do not turn to the next page until the start of the exam.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Answer Key. 1. General Understanding (10 points) think before you decide.

Lecture 5: Implementing Lists, Version 1

Fundamentals of Object Oriented Programming

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

Subclassing for ADTs Implementation

Object-Oriented Design. March 2005 Object Oriented Design 1

16-Dec-10. Consider the following method:

Java Object Oriented Design. CSC207 Fall 2014

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

Programming II (CS300)

CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

CS61B Lecture #11. Please report problems (missing files, malfunctions of submit, etc.) by , not by the newsgroup, for faster service.

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

CSE 331 Final Exam 3/16/15 Sample Solution

CS159. Nathan Sprague


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

COMP1008 Exceptions. Runtime Error

Midterm Exam CS 251, Intermediate Programming March 6, 2015

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

EECS2030 Week 7 worksheet Tue Feb 28, 2017

CS61B Lecture #8. Last modified: Fri Sep 17 12:18: CS61B: Lecture #8 1

Programming II (CS300)

CS558 Programming Languages

CS61B Lecture #12. Public Service Announcement. Miscellaneous Topics: What to do About Errors? throw new SomeException (optional description);

School of Informatics, University of Edinburgh

More on Exception Handling

CSE Programming Languages Final exam - Spring Answer Key

More on Objects in JAVA TM

CS 231 Data Structures and Algorithms, Fall 2016

CS 11 java track: lecture 3

CS 3 Introduction to Software Engineering. 3: Exceptions

More on Exception Handling

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

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

CIS133J. Working with Numbers in Java

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.

CSE P 501 Exam 8/5/04

CS 251 Intermediate Programming Methods and Classes

Inheritance (Part 2) Notes Chapter 6

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Introduction to Programming Using Java (98-388)

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

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

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

Declarations and Access Control SCJP tips

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

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

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017

Give one example where you might wish to use a three dimensional array

Midterm Exam (REGULAR SECTION)

Vendor: Oracle. Exam Code: 1Z Exam Name: Java SE 7 Programmer I. Version: Demo

Class, Variable, Constructor, Object, Method Questions

Pace University. Fundamental Concepts of CS121 1

Lecture 2: Java & Javadoc

GRAMMARS & PARSING. Lecture 7 CS2110 Fall 2013

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

Writing your own Exceptions. How to extend Exception

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

Java Review Outline. basics exceptions variables arrays modulo operator if statements, booleans, comparisons loops: while and for

Title. Java Just in Time. John Latham. February 8, February 8, 2018 Java Just in Time - John Latham Page 1(0/0)

Checked and Unchecked Exceptions in Java

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

INSTRUCTIONS TO CANDIDATES

Question 1. (2 points) What is the difference between a stream and a file?

public static boolean isoutside(int min, int max, int value)

Do not turn to the next page until the start of the exam.

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Inheritance (Part 5) Odds and ends

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

An Introduction to Subtyping

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

CS61B Lecture #11: Examples: Comparable & Reader

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

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

Midterm Exam CS 251, Intermediate Programming March 12, 2014

Recommendation: Play the game and attempt to answer the questions yourself without looking at the answers. You ll learn much less if you just look at

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

Transcription:

CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation of WeirdList by adding a field. Then complete the lines in UseWeirdList (on the next page) such that wlone is a WeirdList containing only the number 1, and wltwoone contains the numbers 2 and 1. Ignore map for now. Throughout this problem, do not use any if, switch, while, for, do, or try statements, and do not use the?: operator. public class WeirdList { private int head; private WeirdList tail; /** The empty sequence of integers. */ public static final WeirdListEmpty EMPTY = new WeirdListEmpty(); /** Returns the number of elements in the sequence that * starts with THIS. */ public int length() { return 1 + tail.length(); public WeirdList(int h, WeirdList t) { head = h; tail = t; /** Apply FUNC.apply to every element of THIS WeirdList in * sequence, and return a WeirdList of the resulting values. */ public WeirdList map(intunaryfunction func) { return new WeirdList(func.apply(head), tail.map(func)); public class WeirdListEmpty extends WeirdList{ public int length() { return 0; public WeirdListEmpty() { super(0, null); public WeirdList map(intunaryfunction func) { return this; /* Return yourself, a WeirdListEmpty. */ public interface IntUnaryFunction { /** Return the result of applying this function to X. */ int apply(int x); CS 61B, Fall 2014, Discussion 5: Inheritance II 1

public class UseWeirdList { /** Sets wlone to be a WeirdList containing one. * and wltwoone to be a WeirdList containing two, then one. */ public static void main(string[] args) { WeirdList wlone = new WeirdList(1, WeirdList.EMPTY); WeirdList wltwoone = new WeirdList(2, wlone); /** Returns the maximum non-negative integer in W. If * no non-negative integers exist, return -1 instead. * Do not use recursion in the code for this method. */ public static int maxpos(weirdlist w) { Maximizer maximizer = new Maximizer(); L.map(maximizer); return maximizer.max; public class Maximizer implements IntUnaryFunction { public int max; public Maximizer() { max = -1; public int apply(int x) { max = Math.max(x, max); return max; Part B. Complete the WeirdListEmpty implementation by filling in the return statement for the map function. If you do not know how to proceed, ask your neighbors. If you know the answer, help out your neighbors. Do it quick, the next part is the intersting part. Part C. Implement the maxpos function. Hint: You ll need to create another class! Do not make recursive calls in your maxpos function or your new class. As throughout this entire problem, do not use any if, switch, while, for, do, or try statements, and do not use the?: operator. Part D. Follow-up: In your solution, did your return value for the apply method matter? The return value of the apply method doesn t matter, because we just end up taking the max member from Maximizer anyway. CS 61B, Fall 2014, Discussion 5: Inheritance II 2

2 TrReader A complete solution to the TrReader problem from Homework 3 is given below. The Reader class is abstract, requires that subclasses implement at least the close() and read(char[], int, int) abstract methods, and provides a default implementation for a no-argument read() method that uses the abstract read(char[], int, int) method to do the real work. public class TrReader extends Reader { private final Reader subreader; private final String from, to; public TrReader(Reader str, String f, String t) { subreader = str; from = f; to = t; public void close() throws IOException { subreader.close(); /** Return translation of single char IN using _FROM and _TO. * e.g. if _FROM="abcdefg", _TO="1234567", IN= c, returns 3 */ private char translateonechar(char in) { /* omitted for brevity */ public int read(char[] cbuf, int off, int len) throws IOException { int numread = _subreader.read(cbuf, off, len); for (int i = off; i < off + numread; i += 1) { cbuf[i] = translateonechar(cbuf[i]); return numread; /* bad style but hey what can you do */ Consider the code below: Reader r = new FileReader("TrReaderTest.java"); Reader trr = new TrReader(r, "import jav.", "josh hug "); System.out.println(trR.read()); For each of the following, state whether the statement is True, False, or Unknown given the information provided. 1. The read(char[], int, int) method is inherited from FileReader by TrReader. F: No TrReader does not extend FileReader 2. Any call to the read(char[], int, int) method of a TrReader object results in a call to the read(char[], int, int) of FileReader. F: No, only if the reader happens to be a FileReader. 3. The call to trr.read() causes a compilation error since we did not define a read() method in TrReader. F: No, a read() method is inherited from Reader. 4. The call to trr.read() results in a call to the read(char[], int, int) method of trr. T: Yes, that s what the default implementation of read() does. CS 61B, Fall 2014, Discussion 5: Inheritance II 3

5. The call to trr.read() results in a call to the read(char[], int, int) method of some instance of the FileReader class. T: Yes, since trr was instantiated with a FileReader. 6. The call to trr.read() results in a call to the read() method of the FileReader class. U: We don t know if FileReader overrides the default read() method. CS 61B, Fall 2014, Discussion 5: Inheritance II 4

3 Extra Questions (not covered in section) These questions might not make sense until you get around to understanding the basics covered in lectures 12 and 13. If this is the case, make sure to go and understand these lectures, and come back to these questions later. 1. The class RuntimeException has many subclasses. Why do they exist? Why don t we always throw a RuntimeException? 2. As we learned in class (if we were there), there are two types of exceptions: Checked Exceptions and Unchecked Exceptions. Any exception which is a subclass of Error or RuntimeException is unchecked. All other exceptions are considered checked. What are the two ways to keep the compiler happy if a method might throw a checked exception? 3. It might seem strange at first that exceptions that are subtypes of Exception or Error are treated differently, and are allowed to pass silently without being caught or specified. Why are these particular exceptions allowed to go unchecked? 4. The protected keyword specifies that a member can be accessed by other components of a package AND by subclasses. If we omit a keyword, a member is considered package protected, and may only be accessed by other package components (i.e. not by any subclasses). Why do you think the Java designers did this? 5. Suppose we have a class BundleOfDogs that stores objects of type Dog, which can be added using a put() method. Suppose that BundleOfDogs also has a method randomdoggenerator() that returns an object of type RandomDog. Suppose that the RandomDog class is implemented as a nested class (i.e. a class inside BundleOfDogs.java). Would it make more sense for RandomDog to be an inner class or a static class? CS 61B, Fall 2014, Discussion 5: Inheritance II 5