CS 215 Software Design Sample midterm solutions

Size: px
Start display at page:

Download "CS 215 Software Design Sample midterm solutions"

Transcription

1 Software Design Sample midterm solutions 1. The administration at Happy Valley School District is redesigning the software that manages information about its students. It has identified an abstract class Student, with two subclasses: ElementaryStudent and MiddleSchoolStudent. MiddleSchoolStudent has a subclass called HighSchoolStudent. The basic organization of these classes is shown below. public abstract class Student { private String name; public class ElementaryStudent extends Student { // This array would have one entry for each year of elementary school // identifying the student s primary teacher private Teacher[] teachers; public class MiddleSchoolStudent extends Student { // All students take the 5 subjects shown below. This remembers who // taught each of those subjects in each year. private Teacher[] mathteacher; private Teacher[] englishteacher; private Teacher[] scienceteacher; private Teacher[] historyteacher; private Teacher[] languageteacher; public class HighSchoolStudent extends MiddleSchoolStudent { // In addition to the subjects in middle school, high school students // can take electives. We need to remember those teachers, too. private Teacher[] elective1teacher; private Teacher[] elective2teacher; private Teacher[] elective3teacher; Suggest another way that this information could be represented and explain what the advantages of your solution are. There is obviously a lot more information that you would want in such a system, but you should not concern yourself with that. Your redesign should keep the same basic information: which teachers did a student have, for which subjects and in which years. In particular, you do not need to model courses, grades, semesters, etc. The use of inheritance in this way is wrong. First, it fails the is-a test because a high school student is not a middle school student. Second, when a student moves from one level of schooling to another, it would be necessary to create a new object to!1

2 represent that student and the previous history of the student would be lost. So, we will first eliminate the inheritance. Using an array that is indexed by the year of school seems like a good way to keep track of which teachers a student had in which years. It would seem good to associate teachers with subjects in a better way than through the variable names. So, we will use a two-dimensional array, where the second dimension is indexed by subject, with subject indexes defined as constants. Finally, for electives, we will just keep an array of elective teachers for each year, indexed by a counter. We end up with a design like this: public class Student { private String name; private static final int MATH = 0; private static final int ENGLISH = 1; private static final int SCIENCE = 2; private static final int HISTORY = 3; private static final int LANGUAGE = 4; private Teacher[] elementaryteachers; private Teacher[][] subjectteachers; private Teacher[][] electiveteachers; Please explain when each of the following ways of writing a method in a superclass and overriding it in a subclass are appropriate. When it says // Code here or // More code here, it means there would be actual code, not just the comment that I show. a. class Superclass { // Code here class Subclass extends Superclass { super.m(); // More code here This is the typical way of overriding a method. It performs the same as the superclass and adds some extra behavior. b. class Superclass { // Code here class Subclass extends Superclass {!2

3 super.m(); There is no point to this. This is overriding a method but doing exactly the same thing as the inherited method. c. class Superclass { // Code here class Subclass extends Superclass { This is a bad idea. One should never override a method to do nothing. An overriding should honor the contract of the method that it overrides, and this almost certainly does not! d. class Superclass { class Subclass extends Superclass { super.m(); // More code here This is the same situation as a. It is a typical overriding, where the superclass implementation did nothing. In general, the implementer of a subclass might not have access to the superclass code and so could not distinguish cases a and d. e. class Superclass { public abstract void m(); class Subclass extends Superclass { super.m(); // More code here This one does not compile. It is not possible to call super.m() since it is abstract. 3. The following questions concern preconditions, postconditions and inheritance. a. For the following class and its description, identify the preconditions and postconditions of the constructor and each method. public Counter() // Initializes a counter to 0 public int getvalue () // Returns the value of the counter public void increment () // Increases the value of the counter by 1 Constructor: no precondition, postcondition value is 0!3

4 getvalue: no precondition, postcondition returns current value increment: no precondition, postcondition value is increased by 1 b. Consider the following subclass of Counter, called Counter2. Identify the preconditions and postconditions of its constructor and methods. Does Counter2 follow the rules about how preconditions and postconditions should change when sub typing? Why or why not? public Counter2() // Initializes a counter to 0 public void increment () // Doubles the value of the counter Constructor: no precondition, postcondition value is set to 0 increment: no precondition, postcondition value is doubled Not a valid subtype because the postcondition has been changed in a way other then strengthening it c. Consider the following subclass of Counter, called Counter3. Identify the preconditions and postconditions of its constructor and methods. Does Counter3 follow the rules about how preconditions and postconditions should change when sub typing? Why or why not? public Counter3() // Initializes a counter to 0 public void increment (int n) // If n > 0, adds n to the value of the // counter Constructor: no precondition, postcondition value is set to 0 increment: precondition n > 0, postcondition value is increased by n This is a valid subtype because this increment function is an overloading, not an overriding.!4

5 4. Take a look at the Java API for Stack available online at 8/docs/api/. a. What problems do you see with where Stack is placed in Java s type hierarchy? Stack extends Vector. That means that there are a lot of non-stack methods that can be applied to and would cause the stack to stop behaving like a Stack. Examples are: add (int index, E element) elementat (index) insertelementat (E obj, int index) remove (int index) remove (Object o) b. Suggest an alternative design that avoids these problems. A better alternative would be to use composition rather than inheritance. In this way Stack would not extend any other classes. It would contain an instance variable whose type is Vector. Any methods that it would have been reasonable to inherit from Vector now become delegation methods. Examples are: capacity() clear() clone() ensurecapacity() isempty() size() trimtosize() c. Discuss your alternative design. What are the advantages and disadvantages of your proposal compared to what Java provides? The modified design has the big advantage that a Stack will always behave like a Stack. With the original design, a Stack can be used anywhere that a Collection is expected. The program could then manipulate the stack in non-stack-like ways, which would likely cause errors. A disadvantage of the modified design is that stacks could be passed as parameters to fewer methods. The more restrictive typing might prevent passing the stack to methods that only operated on it in stack-like ways, but using operations in the Collection interface. For example, if a method only modified a collection by adding and removing at the end, it would be treating the collection as a stack. These calls would no longer be valid. There is also a small disadvantage in the need to write the delegation methods. However, these are very simple to write and should not be a deterrent. Overall, the second design is better because it prevents non-stack-like behavior on the stack. It may be necessary to change some other code or duplicate code in cases where the existing code passes stack as collections but still treats them as stacks.!5

6 5. A Date class consists of the following: public class Date { private int month; private int day; private int year; public Date (int month, int day, int year) { this.month = month; this.day = day; this.year = year; public void adddays (int numdays) { public boolean isleapyear () { a. Describe in English the class invariants for this class. month must be between 1 and 12 day must be between 1 and 31 for months 1, 3, 5, 7, 8, 10, 12 day must be between 1 and 30 for months 4, 6, 9, 11 day must be between 1 and 28 for month 2 when isleapyear returns false day must be between 1 and 29 for month 2 when isleapyear returns true b. Write a wellformed method to check the class invariants. public boolean wellformed () { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return day >= 1 && day <= 31; case 4: case 6: case 9: case 11: return day >= 1 && day <= 30; case 2: if (isleapyear()) return day >= 1 && day <= 29; else return day >= 1 && day <= 28; default: return false;!6

7 c. What are the preconditions and postconditions for the constructor, adddays and isleapyear methods? The constructor s preconditions are the same as the class variant but applied to the parameters. The postcondition is that the Date is well formed. For adddays, there is no precondition. The postcondition is that the Date is modified to be the number of days into the future if the parameter is positive, and the number of days in the past if the parameter is negative. It will wrap around the ends of months and years correctly. For isleapyear, there is no precondition. Its postcondition is that it will return true if the year inside the date is a leap year. It is a leap year if the year is divisible by 4. There are other rules, too, which students might or might not know. (If divisible by 100, it is not a leap year. If divisible by 400, it is a leap year.) d. If you wanted Date objects to be immutable, what would you change about the design above and your answers to the previous parts of this question? I would change the class and instance variables to be final. adddays would return a Date rather than be void. It would return a new date instead of modifying the existing date. e. What are the advantages or disadvantages to having immutable Date objects? With immutable Date objects, there is no need to worry about surprising side effects as a Date can never change. This means that we can treat Dates like values and easily have multiple events on a calendar for example, reference the same Date object without needing to be concerned that moving one event to a different date by calling adddays would affect any other events scheduled for that day. The disadvantage is that whenever we call adddate, we will need to create a new Date object. Overall, it would be preferable for Dates to be immutable. 6. Each of the following has a design flaw. Discuss what the flaw is and suggest a way to remove the flaw. a. public class KeypadLock { private int[] secretcode; public KeyPadLock(int[] code) { secretcode = code; public boolean checkcode (int[] code) { return Arrays.equals(secretCode, code); The array passed to the constructor should be copied into the instance variable. If that is not done, then the part of the program that created the KeypadLock could modify the key or pass the original key around to other parts of the program that could modify the key. That would be an undesirable side effect.!7

8 b. Employee -name -address HourlyEmployee - hourlyrate SalariedEmployee - annualsalary Retired The problem with this hierarchy is that it is trying to capture information with subclasses that is a potentially changing role. For example, an hourly employee might become a salaried employee, or an employee might retire. With the current arrangement, when that type of transition occurs, we would need to create a new object, move the relevant data to the new object, and update all references to the old object to point to the new object. A better solution would be to use composition: Employee -name -address «abstract» EmploymentStatus HourlyEmployee - hourlyrate SalariedEmployee - annualsalary Retired c. public class DailySales { private ArrayList<Sale> sales; // Assume sales is appropriately set. public int totalsales () { int total = 0; for (Sale s : sales) { Payment payment = s.getpayment(); total = total + payment.getamount(); return total; This is a violation of the Law of Demeter, as DailySales should not send methods to an object returned by the getpayment method. A better solution would be to have a method in the Sale class called getamount, that returned the amount directly by asking the Payment object for the amount. Then we would have: public int totalsales () { int total = 0; for (Sale s : sales) {!8

9 total = total + s.getamount(); return total; getamount would look something like this: public int getamount () { return payment.getamount(); 7. For each of the examples below indicate if this is a good use of inheritance or not. If it is not, briefly explain why not and what would be a better way to model the relationship between the classes. a. (3 points) An airplane has a model (like Boeing 747) and belongs to an airline. A flight has a starting and destination airport and a flight number and requires the use of an airplane. Should Flight be modeled as a subclass of Airplane? No, it fails the is-a test. Flight is-not-an airplane. Composition should be used instead. Flight should have an instance variable that is an airplane. b. (3 points) An academic department has many types of employees including teaching assistants and faculty, with one designated faculty member who is the chair of the department. Should Chair be a subtype of Faculty? No, chair is a changing role. Faculty should have a list of roles, of which being a chair is one. And/or Department should have a chair instance variable that refers to the Faculty member currently playing the role of the chair. c. (3 points) A textbook is a book that has questions at the end of each chapter. Should Textbook be a subtype of Book? Yes, this is a good use of inheritance. d. (3 points) A list is an ordered collection of values. An immutable list is a list whose values cannot change after the list is created. Should ImmutableList be a subclass of List? No, ImmutableList and List do not have a shared interface. List s interface would include things like an add method, which would be inappropriate for ImmutableList. It would be better for ImmutableList to have an instance variable whose type is List so it can control the API. e. (3 points) Snickers is the name of my dog. Should Snickers be a subclass of Dog? No, Snickers is not a class. It is an instance of Dog.!9

10 8. Answer the questions below about this UML class diagram. «abstract» BankAccount int balance deposit (int amount) withdraw (int amount) + Customer String name String address openaccount () closeaccount (Account act) CheckingAccount int insufficientfundsfee processcheck (Check c) SavingsAccount double interestrate depositinterest() a. (1 point) What are the names of the methods that can be called on any BankAccount? deposit, withdraw b. (1 point) What are the names of all the methods that can be called on a CheckingAccount? deposit, withdraw, processcheck c. (1 point) How many Customers can be associated with a BankAccount? Exactly 1 d. (1 point) How many BankAccounts can a Customer have? 1 or more e. (1 point) Would the following statement be legal, assuming the constructor exists and the variable cust has type Customer? BankAccount acct = new CheckingAccount (cust); Yes.!10

11 f. (5 points) How would you change the design so that a married couple could share a BankAccount? Draw the revised UML diagram. «abstract» BankAccount int balance deposit (int amount) withdraw (int amount) + AccountHolder openaccount () closeaccount (Account act) CheckingAccount int insufficientfundsfee processcheck (Check c) SavingsAccount double interestrate depositinterest() Customer String name String address 2 MarriedCouple The figure above is one possible solution.!11

12 9. In Java s Collection interface, the add method is described as follows: boolean add(e e) Ensures that this collection contains the specified element. Returns true if this collection changed as a result of the call. Parameters: e - element whose presence in this collection is to be ensured Returns: true if this collection changed as a result of the call a. (2 points) What are the preconditions of Collection s add method? There are no preconditions b. (2 points) What are the postconditions of Collection s add method? e will be in the collection. Returns true if e was not in the collection before add was called and returns false if it was already in the collection. The List interface extends Collection. Its add method is describe as follows: boolean add(e e) Appends the specified element to the end of this list. Parameters: e - element to be appended to this list Returns: true c. (2 points) What are the preconditions of List s add method? There are no preconditions. d. (2 points) What are the postconditions of List s add method? e is added to the end of the list and true is returned. e. (2 points) Does List strengthen, weaken or not change Collection s precondition for add? Not changed f. (2 points) Does List strengthen, weaken or not change Collection s postcondition for add? Strengthen. It indicates where the new element will be and that it always returns true.!12

13 10.I would like you to reason about how Liskov s Substitution Principle helps us understand the subtyping rules associated with generics. The ArrayList class implements the List interface. For this question, focus on the behavior of the get and set methods in the List interface: Interface List<E> E get(int index) Returns the element at the specified position in this list. E set(int index, E element) Replaces the element at the specified position in this list with the specified element a. (2 points) Assuming that Java allows ArrayList<String> to be treated as a subtype of List<String>, does using List and ArrayList in the following way satisfy Liskov s Substitution Principle? Briefly explain your answer. List<String> mylist = new ArrayList<String>(); Yes, this is fine. The signatures of the inherited methods in the ArrayList would all still take Strings as parameters and return Strings as results, so any method defined for List<String> can be called if the object is actually an ArrayList<String> and the caller will not be surprised. b. (2 points) Assuming that Java allows ArrayList<String> to be treated as a subtype of ArrayList<Object>, does using ArrayList in the following way satisfy Liskov s Substitution Principle? Briefly explain your answer. ArrayList<Object> mylist = new ArrayList<String>(); This would not satisfy Liskov s substitution principle. Here the object is supposed to contain just strings. However, when manipulating it via mylist, the add method might insert an object that was not a string, which would surprise someone who thought it should only contain strings. The following code snippet makes the problem clearer. ArrayList<String> mystrings = new ArrayList<String>(); ArrayList<Object> myobjects = mystrings; myobjects.add (new Integer (3)); String lastentry = mystrings.getlast(); Here, we would expect a String result, but the last entry in the ArrayList is actually an Integer. In fact, Java does not allow generics to be subtyped this way. The type of the element cannot change, while the type of the collection can change.!13

CS 215 Software Design Sample Midterm Questions

CS 215 Software Design Sample Midterm Questions Software Design 1. The administration at Happy Valley School District is redesigning the software that manages information about its students. It has identified an abstract class Student, with two subclasses:

More information

CSE 331 Final Exam 3/16/15 Sample Solution

CSE 331 Final Exam 3/16/15 Sample Solution Question 1. (12 points, 3 each) A short design exercise. Suppose Java did not include a Set class in the standard library and we need to store a set of Strings for an application. We know that the maximum

More information

OO Design Principles

OO Design Principles OO Design Principles Software Architecture VO (706.706) Roman Kern Institute for Interactive Systems and Data Science, TU Graz 2018-10-10 Roman Kern (ISDS, TU Graz) OO Design Principles 2018-10-10 1 /

More information

Intro to Computer Science 2. Inheritance

Intro to Computer Science 2. Inheritance Intro to Computer Science 2 Inheritance Admin Questions? Quizzes Midterm Exam Announcement Inheritance Inheritance Specializing a class Inheritance Just as In science we have inheritance and specialization

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Polymorphism 1 / 19 Introduction to Object-Oriented Programming Today we ll learn how to combine all the elements of object-oriented programming in the design of a program that handles a company payroll.

More information

Introduction to Inheritance

Introduction to Inheritance Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits

More information

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

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004 Type Hierarchy Comp-303 : Programming Techniques Lecture 9 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 9 Comp 303 : Programming Techniques Page 1 Last lecture...

More information

Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012

Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012 Why Design by Contract What s the difference with Testing? CS 619 Introduction to OO Design and Development Design by Contract Fall 2012 Testing tries to diagnose (and cure) defects after the facts. Design

More information

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

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit. Name CS 110 Practice Final Exam originally from Winter, 2003 Instructions: closed books, closed notes, open minds, 3 hour time limit. There are 4 sections for a total of 49 points. Part I: Basic Concepts,

More information

CPS122 Lecture: Encapsulation, Inheritance, and Polymorphism

CPS122 Lecture: Encapsulation, Inheritance, and Polymorphism Objectives: CPS122 Lecture: Encapsulation, Inheritance, and Polymorphism Last revised January 23, 2015 1. To review the basic concept of inheritance 2. To introduce Polymorphism. 3. To introduce the notions

More information

Enhanced Entity- Relationship Models (EER)

Enhanced Entity- Relationship Models (EER) Enhanced Entity- Relationship Models (EER) LECTURE 3 Dr. Philipp Leitner philipp.leitner@chalmers.se @xleitix LECTURE 3 Covers Small part of Chapter 3 Chapter 4 Please read this up until next lecture!

More information

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

Logistics. Final Exam on Friday at 3pm in CHEM 102 Java Review Logistics Final Exam on Friday at 3pm in CHEM 102 What is a class? A class is primarily a description of objects, or instances, of that class A class contains one or more constructors to create

More information

CSE 331 Midterm Exam Sample Solution 2/18/15

CSE 331 Midterm Exam Sample Solution 2/18/15 Question 1. (10 points) (Forward reasoning) Using forward reasoning, write an assertion in each blank space indicating what is known about the program state at that point, given the precondition and the

More information

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(a): Abstract Classes Lecture Contents 2 Abstract base classes Concrete classes Dr. Amal Khalifa, 2014 Abstract Classes and Methods

More information

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC Topic 7: Inheritance Reading: JBD Sections 7.1-7.6 1 A Quick Review of Objects and Classes! An object is an abstraction that models some thing or process! Examples of objects:! Students, Teachers, Classes,

More information

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1 References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1 Assertions Statements about input to a routine or state of a class Have two primary roles As documentation,

More information

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics COMP1008 An overview of Polymorphism, Types, Interfaces and Generics Being Object-Oriented Exploiting the combination of: objects classes encapsulation inheritance dynamic binding polymorphism pluggability

More information

Contracts. Dr. C. Constantinides. June 5, Department of Computer Science and Software Engineering Concordia University Montreal, Canada 1/71

Contracts. Dr. C. Constantinides. June 5, Department of Computer Science and Software Engineering Concordia University Montreal, Canada 1/71 Contracts Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada June 5, 2018 1/71 Contracts in human affairs In human affairs we form legally

More information

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

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance

More information

[ L5P1] Object-Oriented Programming: Advanced Concepts

[ L5P1] Object-Oriented Programming: Advanced Concepts [ L5P1] Object-Oriented Programming: Advanced Concepts Polymorphism Polymorphism is an important and useful concept in the object-oriented paradigm. Take the example of writing a payroll application for

More information

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

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course : Advanced Java Concepts + Additional Questions from Earlier Parts of the Course 1. Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... In what order

More information

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13 Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13 Fall 2006 Adapted from Java Concepts Companion Slides 1 Chapter Goals To learn about inheritance To understand how

More information

Array Based Lists. Collections

Array Based Lists. Collections Array Based Lists Reading: RS Chapter 15 1 Collections Data structures stores elements in a manner that makes it easy for a client to work with the elements Specific collections are specialized for particular

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

Assignment 2 - Specifications and Modeling

Assignment 2 - Specifications and Modeling Assignment 2 - Specifications and Modeling Exercise 1 A way to document the code is to use contracts. For this exercise, you will have to consider: preconditions: the conditions the caller of a method

More information

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

Use the scantron sheet to enter the answer to questions (pages 1-6) Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT. Object Oriented Programming BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT Object Oriented Programming Examiner s Report March 2017 A1. a) Explain what is meant by the following terms:

More information

Principles of Software Construction: Objects, Design, and Concurrency. Part 1: Designing Classes. Design for Reuse School of Computer Science

Principles of Software Construction: Objects, Design, and Concurrency. Part 1: Designing Classes. Design for Reuse School of Computer Science Principles of Software Construction: Objects, Design, and Concurrency Part 1: Designing Classes Design for Reuse Charlie Garrod Michael Hilton School of Computer Science 1 Administrivia HW2 due Thursday

More information

Assertions. Assertions - Example

Assertions. Assertions - Example References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 11/13/2003 1 Assertions Statements about input to a routine or state of a class Have two primary roles As documentation,

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

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

Inheritance, cont. Notes Chapter 6 and AJ Chapters 7 and 8 Inheritance, cont. Notes Chapter 6 and AJ Chapters 7 and 8 1 Preconditions and Inheritance precondition what the method assumes to be true about the arguments passed to it inheritance (is-a) a subclass

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM Objectives Defining a wellformed method to check class invariants Using assert statements to check preconditions,

More information

5.6.1 The Special Variable this

5.6.1 The Special Variable this ALTHOUGH THE BASIC IDEAS of object-oriented programming are reasonably simple and clear, they are subtle, and they take time to get used to And unfortunately, beyond the basic ideas there are a lot of

More information

Type Hierarchy. Lecture 6: OOP, autumn 2003

Type Hierarchy. Lecture 6: OOP, autumn 2003 Type Hierarchy Lecture 6: OOP, autumn 2003 The idea Many types have common behavior => type families share common behavior organized into a hierarchy Most common on the top - supertypes Most specific at

More information

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1 Name: CMSC 433 Section 0101 Fall 2012 Midterm Exam #1 Directions: Test is closed book, closed notes. Answer every question; write solutions in spaces provided. Use backs of pages for scratch work. Good

More information

EXAM Computer Science 1 Part 1

EXAM Computer Science 1 Part 1 Maastricht University Faculty of Humanities and Science Department of Knowledge Engineering EXAM Computer Science 1 Part 1 Block 1.1: Computer Science 1 Code: KEN1120 Examiner: Kurt Driessens Date: Januari

More information

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces This week Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces This is a lot of material but we'll be working with these tools the whole semester

More information

Object-oriented basics. Object Class vs object Inheritance Overloading Interface

Object-oriented basics. Object Class vs object Inheritance Overloading Interface Object-oriented basics Object Class vs object Inheritance Overloading Interface 1 The object concept Object Encapsulation abstraction Entity with state and behaviour state -> variables behaviour -> methods

More information

CSE331 Winter 2014, Midterm Examination February 12, 2014

CSE331 Winter 2014, Midterm Examination February 12, 2014 CSE331 Winter 2014, Midterm Examination February 12, 2014 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. Please stop promptly at 11:20. There are 100 points

More information

Basic Object-Oriented Concepts. 5-Oct-17

Basic Object-Oriented Concepts. 5-Oct-17 Basic Object-Oriented Concepts 5-Oct-17 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions, which could manipulate any data An object contains

More information

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

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Department of Computer Engineering Lecture 12: Object-Oriented Principles Sharif University of Technology 1 Open Closed Principle (OCP) Classes should be open for extension but closed

More information

CPS122 Lecture: Detailed Design and Implementation

CPS122 Lecture: Detailed Design and Implementation CPS122 Lecture: Detailed Design and Implementation Objectives: Last revised March 3, 2017 1. To introduce the use of a complete UML class box to document the name, attributes, and methods of a class 2.

More information

COURSE 2 DESIGN PATTERNS

COURSE 2 DESIGN PATTERNS COURSE 2 DESIGN PATTERNS CONTENT Fundamental principles of OOP Encapsulation Inheritance Abstractisation Polymorphism [Exception Handling] Fundamental Patterns Inheritance Delegation Interface Abstract

More information

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

More information

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

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

11/2/09. Code Critique. What goal are we designing to? What is the typical fix for code smells? Refactoring Liskov Substitution Principle

11/2/09. Code Critique. What goal are we designing to? What is the typical fix for code smells? Refactoring Liskov Substitution Principle Code Critique Identifying smells Refactoring Liskov Substitution Principle What goal are we designing to? What is the typical fix for code smells? What is a limitation of those fixes? How do we address

More information

C# Programming for Developers Course Labs Contents

C# Programming for Developers Course Labs Contents C# Programming for Developers Course Labs Contents C# Programming for Developers...1 Course Labs Contents...1 Introduction to C#...3 Aims...3 Your First C# Program...3 C# The Basics...5 The Aims...5 Declaring

More information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

Java: advanced object-oriented features

Java: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: advanced object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Packages

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller Inheritance & Abstract Classes 15-121 Margaret Reid-Miller Today Today: Finish circular queues Exercise: Reverse queue values Inheritance Abstract Classes Clone 15-121 (Reid-Miller) 2 Object Oriented Programming

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecturer: Raman Ramsin Lecture 15: Object-Oriented Principles 1 Open Closed Principle (OCP) Classes should be open for extension but closed for modification. OCP states that we should

More information

Top Down Design vs. Modularization

Top Down Design vs. Modularization 6.170 Quiz Review Topics: 1. Decoupling 2. 3. AF & RI 4. Iteration Abstraction & Iterators 5. OMs and Invariants 6. Equality, Copying, Views 7. 8. Design Patterns 9. Subtyping 10. Case Studies Decomposition

More information

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

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides 1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of

More information

University of Utah School of Computing

University of Utah School of Computing University of Utah School of Computing CS 1410 / CS 2000 Study Notes December 10, 2011 This study guide is designed to help you prepare and study the appropriate material for the final exam. For the multiple

More information

Exam Duration: 2hrs and 30min Software Design

Exam Duration: 2hrs and 30min Software Design Exam Duration: 2hrs and 30min. 433-254 Software Design Section A Multiple Choice (This sample paper has less questions than the exam paper The exam paper will have 25 Multiple Choice questions.) 1. Which

More information

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007 Object Fundamentals Part Three Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007 1 Lecture Goals Continue our tour of the basic concepts, terminology, and notations

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Inheritance (P1 2006/2007)

Inheritance (P1 2006/2007) Inheritance (P1 2006/2007) Fernando Brito e Abreu (fba@di.fct.unl.pt) Universidade Nova de Lisboa (http://www.unl.pt) QUASAR Research Group (http://ctp.di.fct.unl.pt/quasar) Chapter Goals To learn about

More information

Object Oriented Programming COP3330 / CGS5409

Object Oriented Programming COP3330 / CGS5409 Object Oriented Programming COP3330 / CGS5409 Inheritance Assignment 5 Many types of classes that we create can have similarities. Useful to take advantage of the objectoriented programming technique known

More information

CS 520 Theory and Practice of Software Engineering Fall 2018

CS 520 Theory and Practice of Software Engineering Fall 2018 Today CS 520 Theory and Practice of Software Engineering Fall 2018 Object Oriented (OO) Design Principles September 13, 2018 Code review and (re)design of an MVC application (and encapsulation) Polymorphism

More information

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012 Principles of Software Construction: Objects, Design and Concurrency Polymorphism, part 2 15-214 toad Fall 2012 Jonathan Aldrich Charlie Garrod School of Computer Science 2012 C Garrod, J Aldrich, and

More information

CS 1302 Chapter 9 (Review) Object & Classes

CS 1302 Chapter 9 (Review) Object & Classes CS 1302 Chapter 9 (Review) Object & Classes Reference Sections 9.2-9.5, 9.7-9.14 9.2 Defining Classes for Objects 1. A class is a blueprint (or template) for creating objects. A class defines the state

More information

Subtypes and Subclasses

Subtypes and Subclasses Subtypes and Subclasses 6.170 Lecture 14 Fall - ocw.mit.edu Reading: Chapter 7 of Program Development in Java by Barbara Liskov 1 Subtypes We have used closed arrows in module dependence diagrams and object

More information

Advanced JML Erik Poll Radboud University Nijmegen

Advanced JML Erik Poll Radboud University Nijmegen JML p.1/23 Advanced JML Erik Poll Radboud University Nijmegen JML p.2/23 Core JML Remember the core JML keywords were requires ensures signals invariant non null pure \old, \forall, \result JML p.3/23

More information

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

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

PROCESS DEVELOPMENT METHODOLOGY The development process of an API fits the most fundamental iterative code development

PROCESS DEVELOPMENT METHODOLOGY The development process of an API fits the most fundamental iterative code development INTRODUCING API DESIGN PRINCIPLES IN CS2 Jaime Niño Computer Science, University of New Orleans New Orleans, LA 70148 504-280-7362 jaime@cs.uno.edu ABSTRACT CS2 provides a great opportunity to teach an

More information

Inheritance (Part 2) Notes Chapter 6

Inheritance (Part 2) Notes Chapter 6 Inheritance (Part 2) Notes Chapter 6 1 Object Dog extends Object Dog PureBreed extends Dog PureBreed Mix BloodHound Komondor... Komondor extends PureBreed 2 Implementing Inheritance suppose you want to

More information

Exercise 10 Object Structures and Aliasing November 27, 2015

Exercise 10 Object Structures and Aliasing November 27, 2015 Concepts of Object-Oriented Programming AS 2015 Exercise 10 Object Structures and Aliasing November 27, 2015 Task 1 [From a previous exam] In answering this task, do not use reflection, inheritance, and

More information

Inheritance and Substitution (Budd chapter 8, 10)

Inheritance and Substitution (Budd chapter 8, 10) Inheritance and Substitution (Budd chapter 8, 10) 1 2 Plan The meaning of inheritance The syntax used to describe inheritance and overriding The idea of substitution of a child class for a parent The various

More information

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN CSSE 220 Day 15 Inheritance Check out DiscountSubclasses from SVN Discount Subclasses Work in pairs First look at my solution and understand how it works Then draw a UML diagram of it DiscountSubclasses

More information

CSE 331 Software Design and Implementation. Lecture 12 Subtypes and Subclasses

CSE 331 Software Design and Implementation. Lecture 12 Subtypes and Subclasses CSE 331 Software Design and Implementation Lecture 12 Subtypes and Subclasses Zach Tatlock / Winter 2016 The Liskov Substitution Principle Let P(x) be a property provable about objects x of type T. Then

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

EECS2030 Week 7 worksheet Tue Feb 28, 2017

EECS2030 Week 7 worksheet Tue Feb 28, 2017 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

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

Object Oriented Programming: Based on slides from Skrien Chapter 2

Object Oriented Programming: Based on slides from Skrien Chapter 2 Object Oriented Programming: A Review Based on slides from Skrien Chapter 2 Object-Oriented Programming (OOP) Solution expressed as a set of communicating objects An object encapsulates the behavior and

More information

INSTRUCTIONS TO CANDIDATES

INSTRUCTIONS TO CANDIDATES NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING MIDTERM ASSESSMENT FOR Semester 2 AY2017/2018 CS2030 Programming Methodology II March 2018 Time Allowed 90 Minutes INSTRUCTIONS TO CANDIDATES 1. This

More information

Self-review Questions

Self-review Questions 7Class Relationships 106 Chapter 7: Class Relationships Self-review Questions 7.1 How is association between classes implemented? An association between two classes is realized as a link between instance

More information

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8 Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1 Inheritance you know a lot about an object by knowing its class for example what is a Komondor? http://en.wikipedia.org/wiki/file:komondor_delvin.jpg

More information

Making Inheritance Work: C++ Issues

Making Inheritance Work: C++ Issues Steven Zeil September 19, 2013 Contents 1 Base Class Function Members 2 2 Assignment and Subtyping 3 3 Virtual Destructors 5 4 Virtual Assignment 9 5 Virtual constructors 11 51 Cloning 13 6 Downcasting

More information

Making Inheritance Work: C++ Issues

Making Inheritance Work: C++ Issues Steven Zeil September 19, 2013 Contents 1 Base Class Function Members 2 2 Assignment and Subtyping 3 3 Virtual Destructors 4 4 Virtual Assignment 7 5 Virtual constructors 9 51 Cloning 11 6 Downcasting

More information

Software Construction

Software Construction Lecture 7: Type Hierarchy, Iteration Abstraction Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering

More information

Java How to Program, 8/e

Java How to Program, 8/e Java How to Program, 8/e Polymorphism Enables you to program in the general rather than program in the specific. Polymorphism enables you to write programs that process objects that share the same superclass

More information

CS 2102 Exam 1 D-Term 2014

CS 2102 Exam 1 D-Term 2014 NAME: SECTION: CS 2102 Exam 1 D-Term 2014 Question 1: (10) Question 2: (5) Question 3: (15) Question 4: (20) Question 5: (30) Question 6: (20) TOTAL: (100) 1 1. (10 points) Given below are two of the axioms

More information

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

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print) Computer Science 62 Bruce/Mawhorter Fall 16 Midterm Examination October 5, 2016 Question Points Score 1 15 2 10 3 10 4 8 5 9 TOTAL 52 SOLUTIONS Your name (Please print) 1. Suppose you are given a singly-linked

More information

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

Module Contact: Dr Geoff McKeown, CMP Copyright of the University of East Anglia Version 1 UNIVERSITY OF EAST ANGLIA School of Computing Sciences Main Series UG Examination 2015-16 PROGRAMMING 1 CMP-4008Y Time allowed: 2 hours Section A (Attempt all questions: 80 marks) Section B (Attempt one

More information

Originality is Overrated: OO Design Principles

Originality is Overrated: OO Design Principles Originality is Overrated: OO Design Principles Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 13 10/09/2007 University of Colorado, 2007 1 Lecture Goals Review material from

More information

BSc. (Hons.) Software Engineering. Examinations for / Semester 2

BSc. (Hons.) Software Engineering. Examinations for / Semester 2 BSc. (Hons.) Software Engineering Cohort: BSE/04/PT Examinations for 2005-2006 / Semester 2 MODULE: OBJECT ORIENTED PROGRAMMING MODULE CODE: BISE050 Duration: 2 Hours Reading Time: 5 Minutes Instructions

More information

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes Java Curriculum for AP Computer Science, Student Lesson A20 1 STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes INTRODUCTION:

More information

Initial Coding Guidelines

Initial Coding Guidelines Initial Coding Guidelines ITK 168 (Lim) This handout specifies coding guidelines for programs in ITK 168. You are expected to follow these guidelines precisely for all lecture programs, and for lab programs.

More information

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

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information