Complete and fully test the class Person that Exercise 10 describes. Include the following additional methods: getNamereturns

Question:

Complete and fully test the class Person that Exercise 10 describes. Include the following additional methods:

  • getName—returns the name of the person as a string.
  • getAge—returns the age of the person.
  • setName(first, last)—sets the name of the person, given a first and last name as strings.
  • setName(name)—sets the name of the person, given the entire name as one string.
  • setAge(age)—sets the age of the person.
  • createToddler—a static method that returns a special instance of the class to represent a toddler. The instance has the name "A toddler" and the age 2.
  • createPreschooler—a static method that returns a special instance of the class to represent a preschooler. The instance has the name "A preschooler" and the age 5.
  • createAdolescent—a static method that returns a special instance of the class to represent an adolescent. The instance has the name "An adolescent" and the age 9.
  • createTeenager—a static method that returns a special instance of the class to represent a teenager. The instance has the name "A teenager" and the age 15.


Exercise 10

In the previous chapter, Self-Test Question 16 described a class Person to represent a person. The class has instance variables for a person’s name, which is a string, and an integer age. These variables are name and age, respectively.

a. Write a default constructor for Person that sets name to the string "No name yet" and age to zero.

b. Write a second constructor for Person that sets name to a given string and age to a given age.

c. Write a static method createAdult for Person that returns a special instance of this class. The instance represents a generic adult and has the name "An adult" and the age 21.


Self-Test Question 16

Is the following valid, given the class SavingsAccount in Listing 6.7?
SavingsAccount.addInterest();


import java.util.Scanner; /** Class with static and nonstatic members. */ public class SavingsAccount { private double balance; public static double interestRate = 0; public static int number0fAccounts public SavingsAccount () An instance variable (nonstatic) Static variables = 0; { balance 0; A nonstatic method can number0fAccounts++; reference a static variable.

Fantastic news! We've Found the answer you've been seeking!

Step by Step Answer:

Question Posted: