Implementing a New Class
Explore how to implement a Java class with constructors, including default and initializing constructors. Understand method interactions within the class, such as calling one method from another, and learn programming tips for maintaining efficient and error-free code. Discover how to use convenience methods and incorporate a main method to test your class effectively.
We'll cover the following...
The Name class
We finally complete the implementation of the class Name, as shown below:
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 invokes the method getName.
✏️ Programming tip
When feasible, call already defined methods from within the definition of another method in the same class. Doing so avoids ...