

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Reading: Chapter 4 Accessor Methods Accessor methods are used to find out information about an object, without modifying the object. They use the object's instance variables. Let's look at a method to get the year from a Date: getYear() public int getYear() { return year; } Accessor methods have a non-void return type and use the return statement. Draw pic. Mutator methods Mutator methods modify an object. The mutator methods that we have seen are defined with a formal parameter. When the mutator method is called, an argument must be supplied. The value of the argument is assigned to the formal parameter. public void setMonth( int m ) { month = m; } Draw Pic. Some rules about arguments:
Printing Objects using toString() When we print an int or a String, we use System.out.print (or println). In our Date class, we have a method called printDate that we call when we want to print the Date. It would be nice if we could print a Date easily, using System.out. What happens if I try this? Date d1 = new Date( 3, 4, 2005 ); System.out.println( d1 ); How can I make Java do what I want? I can write a special instance method named toString(). It must be defined liked this: public String toString() { } toString is an accessor method - it must return a String containing the information we want to display. public String toString() { return month + "/" + day + "/" + year; } Let's try this When we ask println to display the value of an object, it checks to see if the object has a toString() method. If it does, it calls that method, and then prints the value that is returned.