CPSC 124, Spring 2021: Sample Answers to Quiz #6
These are sample answers only.
Question 1.
The definition of a class named Carrot begins like this:
public class Carrot extends Vegetable {
What is the meaning of "extends Vegetable" here? What effect does it have? What does Vegetable have to be?
Answer. Vegetable must be a class that already exists. Carrot is being declared as as a subclass of Vegetable. This means that it inherits everything from class Vegetable, almost as if it were all retyped in the new class. The Carrot class can then add more variables and can override the methods what it inherits.
Question 2.
A class for representing names, including a first name and a last name, is defined as follows:
public class FullName { private String firstName; // The first name in the full name. private String lastName; // The second name in the full name. public FullName(String first, String last) { // constructor firstName = first; secondName = second; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }
Write one or two Java statements that will declare a variable of type FullName; create an object to represent the name "Jane Doe", whose first name is "Jane" and last name is "Doe"; and store a pointer to that object in the variable. This can be done with one statement that both declares and initializes the variable, or with a statement that declares the variable and another statement to assign a value to it.
Answer.
FullName name; // Declare a variable of type FullName. name = new FullName("Jane", "Doe"); // Create the object by // calling the constructor.
Question 3. This question uses the same class as the previous question:
public class FullName { private String firstName; // The first name in the full name. private String lastName; // The second name in the full name. public FullName(String first, String last) { // constructor firstName = first; secondName = second; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }
Discuss the methods getFirstName() and getLastName(). What are they? Why are they included in this class?
Answer. The methods getFirstName() and getLastName() are "getter" methods for the instance variables firstName and lastName. Since those instance variables are private, the getter methods are needed to let users of the class find out their values. They provide read-only access to the variables (so they are also called "accessor" methods). Since there are no setter methods for the variables, the values of the instance variables can never be changed after being assigned values in the constructor.