SlideShare uma empresa Scribd logo
1 de 5
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Mais procurados (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
 

Semelhante a E6

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
 
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
Mario Fusco
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
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
 

Semelhante a 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
 

Mais 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
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 

Último (20)

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
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...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
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
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
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
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

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