SlideShare a Scribd company logo
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

More Related Content

What's hot

Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
KALAISELVI 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 Type
Philip Schwarz
 
R programming Language
R programming LanguageR programming Language
R programming Language
SarthakBhargava7
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
Programming Homework Help
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
OUM SAOKOSAL
 
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 5
Philip 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 Two
amiable_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 4
Philip Schwarz
 
Computer Science Assignment Help
Computer Science Assignment HelpComputer Science Assignment Help
Computer Science Assignment Help
Programming Homework Help
 
Preparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tablesPreparation Data Structures 09 hash tables
Preparation Data Structures 09 hash tables
Andres Mendez-Vazquez
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
 
The Expression Problem - Part 1
The Expression Problem - Part 1The Expression Problem - Part 1
The Expression Problem - Part 1
Philip Schwarz
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith 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.com
ShwetaAggarwal56
 

What's hot (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
 

Similar to E6

Java Generics
Java GenericsJava Generics
Java Generics
jeslie
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
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
aonesalem
 
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 Know
Kevlin 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
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
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
Henri 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 ii
Prashant Kalkar
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.com
DavisMurphyB81
 
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
mumnesh
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
CodeOps Technologies LLP
 
Hive Functions Cheat Sheet
Hive Functions Cheat SheetHive Functions Cheat Sheet
Hive Functions Cheat Sheet
Hortonworks
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
knutmork
 

Similar to 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
 

More from lksoo

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

More from 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
 

Recently uploaded

Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 

Recently uploaded (20)

Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 

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