EECS2030 Week 7 worksheet Tue Feb 28, 2017

Similar documents
Inheritance, cont. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance (Part 5) Odds and ends

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

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

Inheritance (Part 2) Notes Chapter 6

Free your Lambdas Java SE 8

Inheritance and Interfaces

More on Objects in JAVA TM

CSE 331 Final Exam 3/16/15 Sample Solution

Full file at Chapter 2 - Inheritance and Exception Handling

CS 61B Discussion 5: Inheritance II Fall 2014

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

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

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

More on Exception Handling

Rules and syntax for inheritance. The boring stuff

More on Exception Handling

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

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

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

CmpSci 187: Programming with Data Structures Spring 2015

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Arrays Classes & Methods, Inheritance

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

Inheritance and Polymorphism

Chapter 10 Classes Continued. Fundamentals of Java

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

Collections Algorithms

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

Type Hierarchy. Lecture 6: OOP, autumn 2003

Fundamentals of Object Oriented Programming

Exam Duration: 2hrs and 30min Software Design

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

Module Contact: Dr Geoff McKeown, CMP Copyright of the University of East Anglia Version 1

Declarations and Access Control SCJP tips

CS 61B Discussion 5: Inheritance II Fall 2018

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?

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

16-Dec-10. Consider the following method:

Programming II (CS300)

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

ECE 122. Engineering Problem Solving with Java

Comp 249 Programming Methodology

Creating Java Programs with Greenfoot

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

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

Java Classes, Inheritance, and Interfaces

CSIS 10B Lab 2 Bags and Stacks

Programming II (CS300)

Exception-Handling Overview

Object Oriented Programming 2015/16. Final Exam June 17, 2016

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

CSE wi Midterm Exam 2/8/18 Sample Solution

CS Programming I: Inheritance

Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p no multiple inheritance with classes

CMSC 202. Generics II

CS159. Nathan Sprague

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)

Good Luck! CSC207, Fall 2012: Quiz 3 Duration 25 minutes Aids allowed: none. Student Number: Lecture Section: L0101. Instructor: Horton

CSE 143 Java. Exceptions 1/25/

Programming overview

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

1 Shyam sir JAVA Notes

CO Java SE 8: Fundamentals

Class, Variable, Constructor, Object, Method Questions

Today. Reading. Homework. Lecture Notes CPSC 224 (Spring 2012) hashcode() method. Collections class. Ch 9: hw 7 out (due in a week)

public static void negate2(list<integer> t)

Programming Languages and Techniques (CIS120)

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];


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

COP 3330 Final Exam Review

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

Java Object Oriented Design. CSC207 Fall 2014

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

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

Lexical Ordering and Sorting. These slides refer to interfaces.

Use the scantron sheet to enter the answer to questions (pages 1-6)

CSE 331 Final Exam 3/12/12

Question 2. [12 points] Write a sequence of statements that does the following:

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

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CIS 120 Final Exam 15 December 2017

CS159. Nathan Sprague

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

15CS45 : OBJECT ORIENTED CONCEPTS

CSE wi Midterm Exam 2/8/18. Name UW ID #

INHERITANCE AND EXTENDING CLASSES

Prelim 1. Solution. CS 2110, 14 March 2017, 7:30 PM Total Question Name Short answer

Object-Oriented Concepts

Java Fundamentals (II)

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

CSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin.

Composite Pattern - Shapes Example - Java Sourcecode

APCS Unit 5 Exam. Assuming all four classes have a default constructor, which of the following statements would result in an error from the compiler?

CS61B Lecture #10: OOP mechanism and Class Design. Last modified: Thu Sep 13 16:38: CS61B: Lecture #10 1

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)

Data Abstraction and Specification of ADTs

Transcription:

1. Interfaces The Comparator interface provides a way to control how a sort method (such as Collections.sort) sorts elements of a collection. For example, the following main method sorts a list of strings by their length by using a StringLengthComparator object: public static void main(string[] args) { List<String> t = new ArrayList<>(); t.add("a very very very very long string"); t.add("a short string"); t.add("a medium length string"); Collections.sort(t, new StringLengthComparator()); System.out.println(t); The Comparator interface is defined as follows: public interface Comparator<T> { /** * Compares its two arguments for order. Returns a negative * integer, zero, or a positive integer as the first argument * is less than, equal to, or greater than the second. * * @param o1 the first object to be compared. * @param o2 the second object to be compared. * @return a negative integer, zero, or a positive integer as * the first argument is less than, equal to, or greater than * the second. public int compare(t o1, T o2); //... Implement the class StringLengthComparator so that strings are sorted by their length: public class StringLengthComparator implements Comparator<String> { public int compare(string s, String t) { public class StringLengthComparator implements Comparator<String> { public int compare(string s, String t) { return Integer.compare(s.length(), t.length()); Modify your implementation so that StringLengthComparator first sorts by string length then by dictionary order (i.e., if two strings have the same length then they are sorted by dictionary order):

public class StringLengthComparator implements Comparator<String> { public int compare(string s, String t) { public class StringLengthComparator implements Comparator<String> { public int compare(string s, String t) { int result = Integer.compare(s.length(), t.length()); if (result == 0) { result = s.compareto(t); return result; 2. Inheritance terminology A simplified inheritance hierarchy for the video game Starcraft is shown below: (a) Unit is a superclass of Terran (b) Protoss is a subclass of Unit (c) Zergling is a subclass of Zerg Page 2

(d) Marine is not related to of Protoss (e) Object is an ancestor of Unit 3. Composition instead of inheritance Implement Stack using composition instead of inheritance. public class Stack { private List<Integer> stack; public Stack() { public Stack(Stack other) { public void push(int value) { public int pop() { public class Stack { private List<Integer> stack; public Stack() { this.stack = new ArrayList<>(); public Stack(Stack other) { this.stack = new ArrayList<>(other.stack); public void push(int value) { Page 3

this.stack.add(value); public int pop() { if (this.stack.isempty()) { throw new NoSuchElementException(); return this.stack.remove(this.size() - 1); 4. Subclass constructors Refer back to the figure in Question 2. Every Unit has an amount of health; suppose that the constructors for Unit are implemented like so: public class Unit { private int health; public Unit() { this.health = 1; public Unit(int health) { this.health = health; (a) Implement the Terran constructors; remember that Terran does not have direct access to the field health: public class Terran extends Unit { public Terran() { public Terran(int health) { public class Terran extends Unit { public Terran() { Page 4

super(); public Terran(int health) { super(health); (b) In addition to health, every Protoss unit has an amount of shields. Implement the Protoss constructors: public class Protoss extends Unit { private int shields; // initialize unit to 1 health and 1 shields public Protoss() { public Protoss(int health, int shields) { public class Protoss extends Unit { private int shields; // initialize unit to 1 health and 1 shields public Protoss() { super(); this.shields = 1; public Protoss(int health, int shields) { super(health); this.shields = shields; Page 5

5. Suppose you have a class Y that extends X. X has a method with the following precondition: @pre. value must be a multiple of 2 If Y overrides the method which of the following are acceptable preconditions for the overriding method? Provide a brief statement explaining your answer for each precondition. (a) @pre. value must be a multiple of 2 Acceptable because the precondition is the same as in the superclass. (b) @pre. value must be odd Not acceptable because the precondition of the overriding method does not satisfy the precondition of the parent method. (c) @pre. value must be a multiple of 2 and must be less than 100 Not acceptable because the precondition of the overriding method does not allow for values greater than or equal to 100 whereas the parent method has not such restriction. (d) @pre. value must be a multiple of 10 Not acceptable because the precondition of the overriding method does not allow for all values that are multiples of 2. (e) @pre. none Acceptable because every value that satisfies the parent method precondition also satisfies the precondition of the overriding method. Page 6

6. Suppose you have a class Y that extends X. X has a method with the following postcondition: @return a string of length 10 If Y overrides the method which of the following are acceptable postconditions for the overriding method? Provide a brief statement explaining your answer for each postcondition. (a) @return a string of length at least equal to 10 Not acceptable because strings with length not equal to 10 do not satisfy the postcondition of the parent method. (b) @return the string equal to "weimaraner" Acceptable because "weimaraner" is a string of length 10. (c) @return the empty string Not acceptable because the string with length 0 does not satisfy the postcondition of the parent method. (d) @return a string of length 10 Acceptable because the postcondition is identical to that of the parent method. (e) @return a random string of length 10 Acceptable because a random string of length 10 is a string of length 10. 7. In the Mix class from the lecture slides, which of the following are legal exception specifications? Provide a brief statement explaining your answer for each method header. @Override public void somedogmethod() throws BadDogException Acceptable because BadDogException is substitutable (is a subclass) for DogException (a) @Override public void somedogmethod() throws Exception Not acceptable because Exception is not substitutable for DogException (Exception is an ancestor of DogException) (b) @Override public void somedogmethod() Page 7

Acceptable because no exception is thrown. (c) @Override public void somedogmethod() throws DogException, IllegalArgumentException Trick question. IllegalArgumentException is an unchecked exception and including it in the method header doesn t actually do anything useful. The Java compiler will allow you to write code such as this, so this is technically legal. From a substitutability point of view, this is not acceptable because the overriding method is stating that it can fail (throw an IllegalArgumentException) in situations that the the parent method does not. Page 8