Implementing a New Class
In this lesson, we will finish defining the class Name that we began in the previous lesson.
We'll cover the following...
The Name
class
We finally complete the implementation of the class Name
, as shown below:
/** Name.java by F. M. CarranoA class of names, each containing a first name and a last name.*/public class Name{private String first; // First nameprivate String last; // Last name/** Creates a default name whose first and last names are empty. */public Name(){first = ""; // Empty stringlast = "";} // End default constructor/** Creates a name whose first and last names are the stringsfirstName and lastName, respectively. */public Name(String firstName, String lastName){first = firstName;last = lastName;} // End constructor/** Sets the first name to the string firstName. */public void setFirst(String firstName){first = firstName;} // End setFirst/** Sets the last name to the string lastName. */public void setLast(String lastName){last = lastName;} // End setLast/** Sets the first and last names to the stringsfirstName and lastName, respectively. */public void setName(String firstName, String lastName){setFirst(firstName);setLast(lastName);} // End setName/** Returns the first name as a string. */public String getFirst(){return first;} // End getFirst/** Returns the last name as a string. */public String getLast(){return last;} // End getLast/** Returns the entire name as a string. */public String getName(){return first + " " + last;} // End getName/** Returns the entire name as a string. */public String toString(){return getName();} // End toString/** Gives the last name to otherName. */public void giveLastNameTo(Name otherName){otherName.setLast(last);} // End giveLastNameTo} // End Name
The default constructor sets the data fields to empty strings. If we did not initialize them, Java would set them each to null
. The initializing constructor, as well as the set and get methods, have straightforward definitions.
Notice that some of these methods call each other. In particular, the method setName
calls the methods setFirst
and setLast
. A method can invoke other methods in its class. We write
setFirst(firstName);
For example, in setName
’s body without a receiving object. The object that receives the call to setName
also receives the call to setFirst
. We could write this statement as
this.setFirst(firstName);
if we prefer, but doing so is not necessary. Similarly, the method toString
...