Docsity

Student Class and Inheritance: Java Lab Exercise - Prof. Jennifer E. Walter, Lab Reports of Computer Science

Toggle sidebar
bg1
Recursion and Inheritance
Supplement
CMPU-101: Problem-Solving and
Abstraction
Jennifer Walter
Vassar College
Spring 2008
/** determines whether the given word is a palindrome */
public boolean isWordPal(String word) {
if (word.length() <= 1) {
return true;
} else if (word.charAt(0) == word.charAt(word.length()-1)) {
return this.isWordPal(word.substring(1, word.length()-1));
} else {
return false;
}
}
i. Reuse all the existing code in isWordPal(), adding two additional recursive cases,
described below.
ii. Case 1: if the string starts with a non-letter, then it is a palindrome if the sentence
minus the first character is a palindrome.
iii.Case 2: if the string ends with a non-letter, then it is a palindrome if the sentence
minus the last character is a palindrome.
iv.Finally, you shouldn't compare the first and last characters of the string until
you're sure they're both letters.
Write a recursive method named isLinePal(String line) that returns a boolean
value indicating whether line is a palindrome. Use the above method as a
starting point (add 2 more else-ifs).
Review of Generative Recursion - Lab 11
Classes as Templates for Objects
• All classes are templates for objects, aggregations of data and
behavior. The next four slides walk through the definition of a
class called Student, which is used to keep track of the
following information about a student:
– The name of the student
– The student’s six-digit identification number
– The number of credits the student has earned (which may include a
decimal fraction to account for half- and quarter-credit courses)
• Each of these values is stored in an instance variable of the
appropriate type.
• Instance variables are declared as private. All access to
these values is therefore mediated by public methods
exported by the Student class.
/**
* The Student class keeps track of the following pieces of data
* about a student: the student's name, ID number, and the number
* of credits the student has earned toward graduation.
* All of this information is entirely private to the class.
* Clients can obtain this information only by using the various
* methods defined by the class.
*/
public class Student { // Note the lack of "extends" clause
/** 2-parameter constructor
* Creates a new Student object with the specified name and ID.
* name: The student's name as a String
* id: The student's ID number as an int
*/
public Student(String name, int id) {
this.studentName = name;
this.studentID = id;
}
The Student Class
This comment describes the class as a whole.
The class header defines Student as a direct subclass of Object.
This comment describes the constructor.
The constructor sets the instance variables.
skip code
/**
* The Student class keeps track of the following pieces of data
* about a student: the student's name, ID number, the number of
* credits the student has earned toward graduation, and whether
* the student is paid up with respect to university bills.
* All of this information is entirely private to the class.
* Clients can obtain this information only by using the various
* methods defined by the class.
*/
public class Student {
/**
* Creates a new Student object with the specified name and ID.
* @param name The student's name as a String
* @param id The student's ID number as an int
*/
public Student(String name, int id) {
studentName = name;
studentID = id;
}
/**
* Returns the name of this student
*/
public String getName() {
return this.studentName;
}
/**
* Returns the ID number of this student.
*
*/
public int getID() {
return this.studentID;
}
/**
* Sets the number of credits earned.
* credits is the new number of credits earned
*/
public void setCredits(double credits) {
this.creditsEarned = credits;
}
The Student Class
These methods retrieve the value of
an instance variable and are called
getters. Because the student name
and ID number are fixed, there are
no corresponding setters.
This method cha nges the value of
an instance variable and is called a
setter.
skip code
/**
* Gets the number of credits earned.
* @return The number of credits this student has earned
*/
public double getCredits() {
return creditsEarned;
}
/**
* Sets whether the student is paid up.
* @param flag The value true or false indicating paid-up status
*/
public void setPaidUp(boolean flag) {
paidUp = flag;
}
/**
* Returns whether the student is paid up.
* @return Whether the student is paid up
*/
public boolean isPaidUp() {
return paidUp;
}
/**
* Creates a string identifying this student.
* Return the string used to display this student
*/
public String toString() {
return this.studentName +
" (#" + this.studentID + ")"; }
/* Public constants */
/** The number of credits required for graduation */
public static final double CREDITS_TO_GRADUATE = 34.0;
/* Private instance variables */
private String studentName; /* The student's name */
private int studentID; /* The student's ID number */
private double creditsEarned; /* The number of credits earned */
}
The Student Class
The toString method
tells Java how to display
a value of this class. All
of your classes should
override toString.
Classes often export named constants.
These declarations define the instance
variables that maintain the internal
state of the class. All instance variables
used in the text are private.
skip code
pf3
pf4

Partial preview of the text

Download Student Class and Inheritance: Java Lab Exercise - Prof. Jennifer E. Walter and more Lab Reports Computer Science in PDF only on Docsity!

Recursion and Inheritance

Supplement

CMPU-101: Problem-Solving and

Abstraction

Jennifer Walter

Vassar College

Spring 2008

/** determines whether the given word is a palindrome */ public boolean isWordPal(String word) { if (^) return(word.length() true; <= 1) { } else return if this.(word.isWordPalcharAt(0)(word.substring(1, == word.charAt(word.length()-1)) word.length()-1)); { } else return { false; }^ }

i. Reuse all the existing code in isWordPal(), adding two additional recursive cases,

described below.

ii. Case 1: if the string starts with a non-letter, then it is a palindrome if the sentence

minus the first character is a palindrome.

iii.Case 2: if the string ends with a non-letter, then it is a palindrome if the sentence

minus the last character is a palindrome.

iv.Finally, you shouldn't compare the first and last characters of the string until

you're sure they're both letters.

Write a recursive method named isLinePal(String line) that returns a boolean

value indicating whether line is a palindrome. Use the above method as a

starting point (add 2 more else-ifs).

Review of Generative Recursion - Lab 11

Classes as Templates for Objects

• All classes are templates for objects , aggregations of data and

behavior. The next four slides walk through the definition of a

class called Student, which is used to keep track of the

following information about a student:

  • The name of the student
  • The student’s six-digit identification number
  • The number of credits the student has earned (which may include a decimal fraction to account for half- and quarter-credit courses)

• Each of these values is stored in an instance variable of the

appropriate type.

• Instance variables are declared as private. All access to

these values is therefore mediated by public methods

exported by the Student class.

* The Student class keeps track of the following pieces of data

* about a student: the student's name, ID number, and the number

* of credits the student has earned toward graduation.

* All of this information is entirely private to the class.

* Clients can obtain this information only by using the various

* methods defined by the class.

public class Student { // Note the lack of "extends" clause

/** 2-parameter constructor

* Creates a new Student object with the specified name and ID.

* name: The student's name as a String

* id: The student's ID number as an int

public Student(String name, int id) {

this.studentName = name;

this.studentID = id;

The Student Class

This comment describes the class as a whole. The class header defines Student as a direct subclass of Object_. This comment describes the constructor. The constructor sets the instance variables. skip code_

* The Student class keeps track of the following pieces of data

* about a student: the student's name, ID number, the number of

* credits the student has earned toward graduation, and whether

* the student is paid up with respect to university bills.

* All of this information is entirely private to the class.

* Clients can obtain this information only by using the various

* methods defined by the class.

public class Student {

* Creates a new Student object with the specified name and ID.

* @param name The student's name as a String

* @param id The student's ID number as an int

public Student(String name, int id) {

studentName = name;

studentID = id;

* Returns the name of this student

public String getName() {

return this.studentName;

* Returns the ID number of this student.

public int getID() {

return this.studentID;

* Sets the number of credits earned.

* credits is the new number of credits earned

public void setCredits(double credits) {

this.creditsEarned = credits;

The Student Class

These methods retrieve the value of an instance variable and are called getters and ID number are fixed, there are. Because the student name no corresponding setters. This method changes the value of an instance variable and is called a setter. skip code

* Gets the number of credits earned.

* @return The number of credits this student has earned

public double getCredits() {

return creditsEarned;

* Sets whether the student is paid up.

* @param flag The value true or false indicating paid-up status

public void setPaidUp(boolean flag) {

paidUp = flag;

* Returns whether the student is paid up.

* @return Whether the student is paid up

public boolean isPaidUp() {

return paidUp;

* Creates a string identifying this student.

* Return the string used to display this student

public String toString() {

return this.studentName +

" (#" + this.studentID + ")"; }

/* Public constants */

/** The number of credits required for graduation */

public static final double CREDITS_TO_GRADUATE = 34.0;

/* Private instance variables */

private String studentName; /* The student's name */

private int studentID; /* The student's ID number */

private double creditsEarned; /* The number of credits earned */

The Student Class

The tells Java how to display toString method a value of this class. All of your classes should override toString_. Classes often export named constants. These declarations define the instance variables that maintain the internal state of the class. All instance variables used in the text are private. skip code_

Using the Student Class

• Once you have defined the Student class, you can then use

its constructor to create instances of that class (objects). For

example, you could use the following code to declare and

instantiate two Student objects with variable names shown:

Student chosenOne = new Student("Harry Potter", 123456);

Student topStudent = new Student("Hermione Granger", 314159);

• You can then use the standard receiver syntax to call methods

on these objects. For example, you could set Hermione’s

number-of-credits field to 97 by writing

or get Harry’s full name by calling

topStudent.setCredits(97);

chosenOne.getName();

Extending Existing Classes

• All programs you write are classes and all classes extend the

built-in Object class. Sometimes you will find that you

want to extend an existing class to create a new class that

inherits most of its behavior from its superclass but makes

some small extensions or changes.

• Suppose, for example, that you wanted to define a new class

called FilledRect that is similar to the GRect class, except

that it is filled rather than outlined by default. Moreover, as a

convenience, you would like to be able to specify an optional

color for the rectangle as part of the constructor. Calling

this.add(new FilledRect(10, 10, 100, 75, Color.RED));

for example, should create a 100x75 rectangle solidly filled in

red and then add it to the canvas at the point (10, 10).

• The code for the FilledRect class appears on the next slide.

The FilledRect Class

* This class is a GRect subclass that is almost identical

* to GRect except that it starts out filled instead of outlined.

public class FilledRect extends GRect {

/** Creates a new FilledRect with the specified bounds. */

public FilledRect(double x, double y,

double width, double height) {

super(x, y, width, height);

setFilled(true);

/** Creates a new FilledRect with the specified bounds and color. */

public FilledRect(double x, double y,

double width, double height, Color color) {

this(x, y, width, height);

setColor(color);

This syntax calls the superclass constructor. This calls the 4-parameter constructor in this class.

Rules for Inherited Constructors

• Whenever you create an object of an extended class, Java

must call some constructor for the superclass object to ensure

that its structure is correctly initialized.

• If the superclass does not define any explicit constructors,

Java automatically provides a default zero-parameter

constructor in the superclass with an empty body.

• Java therefore invokes the superclass constructor in one of the

following ways:

  • Constructors that begin with an explicit call to this invoke one of the other constructors for this class, delegating responsibility to that constructor for making sure that the superclass constructor gets called.
  • Constructors that begin with a call to super invoke the constructor in the superclass that matches the argument list provided.
  • Constructors that begin with no call to either super or this invoke the default superclass constructor with no arguments.

Rules for Inherited Methods

• When one class extends another, the subclass may override

methods that are defined in any of its superclasses. Whenever

you invoke an overridden method on an object, Java chooses

the version of the method defined lowest in the hierarchy on

the actual type of the object.

• When a class implements an interface, the subclass must

override method definitions in its superclass. Interfaces are

used to define a suite of methods that are shared by all

implementing classes.

Rules for Inherited Methods

• The decision about which version of a method to use, the

super- or the subclass method, is always made on the basis of

what the object in fact is and not on what it happens to be

declared as.

• Even though an object may be declared as its supertype, it is

the type for which the constructor was called using the new

keyword.

• When we declare a union of classes like we did with IList, the

recursive methods end when the rest of the ConsList is an

object whose type is MTList. Java knows whether to call the

method for an MTList or a ConsList because of how we build

a Conslist ( we have to start with innermost "new MTList()" ).

/* Print original lists / this.println(" naturals = " + naturals); this.println(" mt = "+ mt); this.println(" boringList = "+ boringList); / this. Testprintln the recursive("\nTesting methods recursive on our methods..."); lists */ this.println(" naturals.length() should be 6 and is " + naturals.length()); this.println(" mt.length should be 0 and is "+ mt.length()); this.println("\n naturals.contains(4) should be true and is "+ naturals.contains(4)); this.println(" naturals.contains(7) should be false and is "+ naturals.contains(7)); this.println(" mt.contains(4) should be false and is "+ mt.contains(4)); }

The TestIList Class

  • create a new IList that contains all the numbers from
  • 1 to n in ascending order / private IList makeList(int n) { IList tempList = new MTList(); for (int i = n; i >=1; i--) { tempList = new ConsList(i,tempList); } return tempList; } /*
  • create a new IList that contains numbers read from the user */ private IList readList() { IList tempList = new MTList(); int n = 0; while ((n = readInt("(Enter pos int or 0 to quit): ")) > 0) { tempList = new ConsList(n,tempList); } return tempList; } }

The TestIList Class

Methods called on ILists

Write a method called getIth(int x) to return

the ith element of an IList.

Write a method add(int x) that is called on an IList

and that returns the IList with x appended to the

end.