SlideShare une entreprise Scribd logo
1  sur  5
Télécharger pour lire hors ligne
CS211 Computers and Programming 
Matthew Harris and Alexa Sharp July 8, 2002 
Exam 1 Solutions 
Recursion, Induction, and Object-Oriented Programming 
Problems 
1. Recursion 
public abstract class Word { 
public static Word fromString(String in) { 
return fromString_startingAt(in, 0); 
} 
private static Word fromString_startingAt(String in, int pos) { 
if (in.length() > pos) 
return new Letter(in.charAt(pos), 
fromString_startingAt(in, pos+1)); 
else 
return new Empty(); 
} 
public abstract String toString(); 
public abstract boolean equals(Object other); 
public Word reverse() { 
return reverse_helper(new Empty()); 
} 
protected abstract Word reverse_helper(Word temp); 
public boolean isPalendrome() { 
return equals(reverse()); 
} 
} 
class Empty extends Word { 
public String toString() { // -- Complete this 
return ""; 
} 
public boolean equals(Object other) { // -- Complete this 
return other instanceof Empty; 
} 
protected Word reverse_helper(Word temp) { 
return temp; 
} 
} 
1
CS211 Computers and Programming 
Matthew Harris and Alexa Sharp July 8, 2002 
class Letter extends Word { 
char first; 
Word rest; // not null 
public Letter(char first, Word rest) { 
this.first = first; 
this.rest = rest; 
} 
public String toString() { // -- Complete this 
return first + rest.toString(); 
} 
public boolean equals(Object other) { // -- Complete this 
return other instanceof Letter 
&& first == ((Letter)other).first 
&& rest.equals(((Letter)other).rest); 
} 
protected Word reverse_helper(Word temp) { 
return rest.reverse_helper(new Letter(first, temp)); 
} 
} 
2. Induction 
Proof of correctness of reverse_helper: 
P(e): e.reverse_helper(e2) for any Word e2 returns the Word consisting of 
the letters of e in reverse order followed by the letters of e2. 
Proof by structural induction: 
Base case: If e is Empty, then e2 is returned, so P(e) is true. 
Induction step: Assume that P(e) is true for some Word e. (This is our 
inductive hypothesis.) Construct an e1 = new Letter(c,e). Then 
e1.reverse_helper(e2) returns the value e.reverse helper(new 
Letter(c,e2)), which by the inductive hypothesis is the Word con-sisting 
of the letters of e in reverse order followed by c and the letters 
of e2. This is the same as the letters of e1 in reverse order followed 
by the letters of e2, so P(e1) is true. 
2
CS211 Computers and Programming 
Matthew Harris and Alexa Sharp July 8, 2002 
3. Inheritance 
(a) Suppose we would like an Instrument class. Write the Java code for it be-low. 
What are the fields and method(s)? Don’t forget to write a construc-tor 
(one non-empty one will suffice). You don’t have to fill in the body of 
your method (though you do need to write the constructor body). 
class Instrument { 
// Fields 
protected int minPitch; 
protected int maxPitch; 
// Constructor 
public Instrument( int minPitch, int maxPitch ) { 
this.minPitch = minPitch; 
this.maxPitch = maxPitch; 
} 
// Method 
public void playRange() { } 
} 
(b) Suppose I’d like to make a class each for StringInstrument and Percus-sionInstrument. 
Write the Java code for it below. What would the fields 
and methods be for each type of instrument? Don’t forget a non-empty 
constructor for each! Again, you can ignore the body of the method. 
See the listing on the next page. 
(c) Draw an inheritance diagram representing the hierarchy described. 
Instrument 
/  
/  
StringInstrument PercussionInstrument 
(d) Suppose I’d like to make a new class in Java to encompass this string-percussion 
instrument. Given the above classes, what particular problem 
will I encounter? What is the solution to this problem? 
The problem is that I would like to create a new class that ex-tends 
both StringInstrument and PercussionInstrument. Java 
only allows you to extend one class, though. The solution to this 
problem is interfaces. I would create one interface for Instrument, 
one for StringInstrument, and one for PercussionInstrument. 
My hybrid class would implement the combination of these three 
interfaces. 
4. Short Answer 
(a) What are two advantages of encapsulation/information hiding? 
• It places related code together. (encapsulation) 
• It divides code into objects that model real-life entities. (en-capsulation) 
3
CS211 Computers and Programming 
Matthew Harris and Alexa Sharp July 8, 2002 
class StringInstrument extends Instrument { 
// Fields 
protected int numberOfStrings; 
protected boolean isBowed; 
// Constructor 
public StringInstrument( int minPitch, int maxPitch, 
int numberOfStrings, boolean isBowed ) { 
super( minPitch, maxPitch ); 
this.numberOfStrings = numberOfStrings; 
this.isBowed = isBowed; 
} 
// Method 
public void tune() { } 
} 
class PercussionInstrument extends Instrument { 
// Fields 
protected boolean isSinglePitch; 
protected boolean isMembranophone; 
// Constructor 
public PercussionInstrument( int minPitch, int maxPitch, 
boolean isSinglePitch, 
boolean isMembranophone ) { 
super( minPitch, maxPitch ); 
this.isSinglePitch = isSinglePitch; 
this.isMembranophone = isMembranophone; 
} 
// Method 
public void strike() { } 
} 
4
CS211 Computers and Programming 
Matthew Harris and Alexa Sharp July 8, 2002 
• It prevents abusive users from accessing/modifying the inner 
workings of an object. (information hiding) 
• It lets the programmer make code changes without affecting 
the user’s code. (information hiding) 
(b) What is the difference between a public field and a protected field? 
A public field can be accessed from outside the class and is inher-ited. 
A protected field cannot be accessed from outside the class, 
but is also inherited. 
(c) Suppose class SciFiMovie and class ComedyMovie are subclasses of class 
Movie. Which of the following are legal? 
ComedyMovie c = new Movie(); // illegal 
Movie m = new SciFiMovie(); // legal 
SciFiMovie s = new ComedyMovie(); // illegal 
(d) Why would you make a method (and hence class) abstract? 
If there were a method, m say, that I would like all subclasses to 
have, but has no meaning in the superclass itself then I would 
make m abstract in the superclass. This would declare m()’s sig-nature 
in the abstract superclass, and all subclasses would either 
have to implement m or be abstract themselves. 
(e) I have the following incomplete implementation of a IntArrayIterator 
class, that iterates over an array of integers. Fill in the remaining portion 
of the next() method. 
class ListIterator implements Iterator { 
int[] myArray; // an array over which I want to iterate 
int cursor; // my current position in my array 
// constructor 
public ListIterator( int[] myArray ) { this.myArray = myArray; } 
// Returns true if there is another element to return 
boolean hasNext() { return cursor < myArray.length; } 
// Returns the next element to return 
Object next() throws NoSuchElementException { 
// If there are no elements left, throw an exception 
if( !hasNext() ) 
throw new NoSuchElementException(); 
// Otherwise, return the next element, etc. 
else { 
// FILL IN HERE 
return myList[cursor++]; 
} 
} 
} 
5

Contenu connexe

Tendances

Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc csKALAISELVI P
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypePhilip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Gamindu Udayanga
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Philip Schwarz
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)teach4uin
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Philip Schwarz
 
Preparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tablesPreparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tablesAndres Mendez-Vazquez
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
The Expression Problem - Part 1
The Expression Problem - Part 1The Expression Problem - Part 1
The Expression Problem - Part 1Philip Schwarz
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comShwetaAggarwal56
 

Tendances (20)

Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
 
Beginning Python
Beginning PythonBeginning Python
Beginning Python
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data Type
 
python.ppt
python.pptpython.ppt
python.ppt
 
R programming Language
R programming LanguageR programming Language
R programming Language
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 
Computer Science Assignment Help
Computer Science Assignment HelpComputer Science Assignment Help
Computer Science Assignment Help
 
Preparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tablesPreparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tables
 
Python programming
Python  programmingPython  programming
Python programming
 
Python language data types
Python language data typesPython language data types
Python language data types
 
The Expression Problem - Part 1
The Expression Problem - Part 1The Expression Problem - Part 1
The Expression Problem - Part 1
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.com
 

Similaire à E6

Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Main issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfMain issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfaonesalem
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)Tak Lee
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already KnowKevlin Henney
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingHenri Tremblay
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancementRakesh Madugula
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.comDavisMurphyB81
 
Rooms and MoreCan you please help me the JAVA programLabInherit.pdf
Rooms and MoreCan you please help me the JAVA programLabInherit.pdfRooms and MoreCan you please help me the JAVA programLabInherit.pdf
Rooms and MoreCan you please help me the JAVA programLabInherit.pdfmumnesh
 
Hive Functions Cheat Sheet
Hive Functions Cheat SheetHive Functions Cheat Sheet
Hive Functions Cheat SheetHortonworks
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 

Similaire à E6 (20)

Java Generics
Java GenericsJava Generics
Java Generics
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Main issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfMain issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdf
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already Know
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Java execise
Java execiseJava execise
Java execise
 
Jeop game-final-review
Jeop game-final-reviewJeop game-final-review
Jeop game-final-review
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Lec2
Lec2Lec2
Lec2
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.com
 
Rooms and MoreCan you please help me the JAVA programLabInherit.pdf
Rooms and MoreCan you please help me the JAVA programLabInherit.pdfRooms and MoreCan you please help me the JAVA programLabInherit.pdf
Rooms and MoreCan you please help me the JAVA programLabInherit.pdf
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Hive Functions Cheat Sheet
Hive Functions Cheat SheetHive Functions Cheat Sheet
Hive Functions Cheat Sheet
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 

Plus de lksoo

Plus de lksoo (20)

Lo48
Lo48Lo48
Lo48
 
Lo43
Lo43Lo43
Lo43
 
Lo39
Lo39Lo39
Lo39
 
Lo37
Lo37Lo37
Lo37
 
Lo27
Lo27Lo27
Lo27
 
Lo17
Lo17Lo17
Lo17
 
Lo12
Lo12Lo12
Lo12
 
T3
T3T3
T3
 
T2
T2T2
T2
 
T1
T1T1
T1
 
T4
T4T4
T4
 
P5
P5P5
P5
 
P4
P4P4
P4
 
P3
P3P3
P3
 
P1
P1P1
P1
 
P2
P2P2
P2
 
L10
L10L10
L10
 
L9
L9L9
L9
 
L8
L8L8
L8
 
L7
L7L7
L7
 

Dernier

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 

Dernier (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

E6

  • 1. CS211 Computers and Programming Matthew Harris and Alexa Sharp July 8, 2002 Exam 1 Solutions Recursion, Induction, and Object-Oriented Programming Problems 1. Recursion public abstract class Word { public static Word fromString(String in) { return fromString_startingAt(in, 0); } private static Word fromString_startingAt(String in, int pos) { if (in.length() > pos) return new Letter(in.charAt(pos), fromString_startingAt(in, pos+1)); else return new Empty(); } public abstract String toString(); public abstract boolean equals(Object other); public Word reverse() { return reverse_helper(new Empty()); } protected abstract Word reverse_helper(Word temp); public boolean isPalendrome() { return equals(reverse()); } } class Empty extends Word { public String toString() { // -- Complete this return ""; } public boolean equals(Object other) { // -- Complete this return other instanceof Empty; } protected Word reverse_helper(Word temp) { return temp; } } 1
  • 2. CS211 Computers and Programming Matthew Harris and Alexa Sharp July 8, 2002 class Letter extends Word { char first; Word rest; // not null public Letter(char first, Word rest) { this.first = first; this.rest = rest; } public String toString() { // -- Complete this return first + rest.toString(); } public boolean equals(Object other) { // -- Complete this return other instanceof Letter && first == ((Letter)other).first && rest.equals(((Letter)other).rest); } protected Word reverse_helper(Word temp) { return rest.reverse_helper(new Letter(first, temp)); } } 2. Induction Proof of correctness of reverse_helper: P(e): e.reverse_helper(e2) for any Word e2 returns the Word consisting of the letters of e in reverse order followed by the letters of e2. Proof by structural induction: Base case: If e is Empty, then e2 is returned, so P(e) is true. Induction step: Assume that P(e) is true for some Word e. (This is our inductive hypothesis.) Construct an e1 = new Letter(c,e). Then e1.reverse_helper(e2) returns the value e.reverse helper(new Letter(c,e2)), which by the inductive hypothesis is the Word con-sisting of the letters of e in reverse order followed by c and the letters of e2. This is the same as the letters of e1 in reverse order followed by the letters of e2, so P(e1) is true. 2
  • 3. CS211 Computers and Programming Matthew Harris and Alexa Sharp July 8, 2002 3. Inheritance (a) Suppose we would like an Instrument class. Write the Java code for it be-low. What are the fields and method(s)? Don’t forget to write a construc-tor (one non-empty one will suffice). You don’t have to fill in the body of your method (though you do need to write the constructor body). class Instrument { // Fields protected int minPitch; protected int maxPitch; // Constructor public Instrument( int minPitch, int maxPitch ) { this.minPitch = minPitch; this.maxPitch = maxPitch; } // Method public void playRange() { } } (b) Suppose I’d like to make a class each for StringInstrument and Percus-sionInstrument. Write the Java code for it below. What would the fields and methods be for each type of instrument? Don’t forget a non-empty constructor for each! Again, you can ignore the body of the method. See the listing on the next page. (c) Draw an inheritance diagram representing the hierarchy described. Instrument / / StringInstrument PercussionInstrument (d) Suppose I’d like to make a new class in Java to encompass this string-percussion instrument. Given the above classes, what particular problem will I encounter? What is the solution to this problem? The problem is that I would like to create a new class that ex-tends both StringInstrument and PercussionInstrument. Java only allows you to extend one class, though. The solution to this problem is interfaces. I would create one interface for Instrument, one for StringInstrument, and one for PercussionInstrument. My hybrid class would implement the combination of these three interfaces. 4. Short Answer (a) What are two advantages of encapsulation/information hiding? • It places related code together. (encapsulation) • It divides code into objects that model real-life entities. (en-capsulation) 3
  • 4. CS211 Computers and Programming Matthew Harris and Alexa Sharp July 8, 2002 class StringInstrument extends Instrument { // Fields protected int numberOfStrings; protected boolean isBowed; // Constructor public StringInstrument( int minPitch, int maxPitch, int numberOfStrings, boolean isBowed ) { super( minPitch, maxPitch ); this.numberOfStrings = numberOfStrings; this.isBowed = isBowed; } // Method public void tune() { } } class PercussionInstrument extends Instrument { // Fields protected boolean isSinglePitch; protected boolean isMembranophone; // Constructor public PercussionInstrument( int minPitch, int maxPitch, boolean isSinglePitch, boolean isMembranophone ) { super( minPitch, maxPitch ); this.isSinglePitch = isSinglePitch; this.isMembranophone = isMembranophone; } // Method public void strike() { } } 4
  • 5. CS211 Computers and Programming Matthew Harris and Alexa Sharp July 8, 2002 • It prevents abusive users from accessing/modifying the inner workings of an object. (information hiding) • It lets the programmer make code changes without affecting the user’s code. (information hiding) (b) What is the difference between a public field and a protected field? A public field can be accessed from outside the class and is inher-ited. A protected field cannot be accessed from outside the class, but is also inherited. (c) Suppose class SciFiMovie and class ComedyMovie are subclasses of class Movie. Which of the following are legal? ComedyMovie c = new Movie(); // illegal Movie m = new SciFiMovie(); // legal SciFiMovie s = new ComedyMovie(); // illegal (d) Why would you make a method (and hence class) abstract? If there were a method, m say, that I would like all subclasses to have, but has no meaning in the superclass itself then I would make m abstract in the superclass. This would declare m()’s sig-nature in the abstract superclass, and all subclasses would either have to implement m or be abstract themselves. (e) I have the following incomplete implementation of a IntArrayIterator class, that iterates over an array of integers. Fill in the remaining portion of the next() method. class ListIterator implements Iterator { int[] myArray; // an array over which I want to iterate int cursor; // my current position in my array // constructor public ListIterator( int[] myArray ) { this.myArray = myArray; } // Returns true if there is another element to return boolean hasNext() { return cursor < myArray.length; } // Returns the next element to return Object next() throws NoSuchElementException { // If there are no elements left, throw an exception if( !hasNext() ) throw new NoSuchElementException(); // Otherwise, return the next element, etc. else { // FILL IN HERE return myList[cursor++]; } } } 5