Page 550 - Introduction to Programming with Java: A Problem Solving Approach
P. 550

                516 Chapter 13 Inheritance and Polymorphism
 /******************************************************
*
Car2.java
Dean & Dean
This instantiates a car and displays its properties.
******************************************************/
*
*
*
public class Car2
{
private String make; // car's make
private int year;
// car's listed year
private String color; // car's color
//***************************************************
public Car2(String make, int year, String color)
{
this.make = make;
this.year = year;
this.color = color;
// end Car2 constructor
//***************************************************
         Apago PDF Enhancer
public String toString() ⎫ ⎪
}
  }
// end class Car2
{⎪ return "make = " + make + ", year = " + year + ⎬
", color = " + color; ⎪ ⎪
} // end toString ⎭ //***************************************************
public static void main(String[] args)
{
}
Car2 car = new Car2("Honda", 1998, "silver");
System.out.println(car);
// end main
This overrides the Object class’s toString method.
Figure 13.2 Car2 program that illustrates overriding toString method
Note that you’ll often see the toString method explicitly called with the standard call syntax even when it’s not necessary. For example, in the Counter program’s main method, we might have used this al- ternative implementation for the message assignment statement:
String message = "Current count = " + counter.toString();
Some programmers would claim that this alternative implementation is better because the code is more self- documenting. Some programmers would claim that the original implementation is better because the code is more compact. We don’t have a preference as to which implementation is better—either way is fine.
























































   548   549   550   551   552