reset password
Author Message
rabbott
Posts: 1649
Posted 12:07 Oct 16, 2013 |

Yesterday we talked about an example that looked something like this.

public class Time
{
    private int hours;   
    private int minutes;

    /**
     * Constructor for objects of class Time
     */
    public Time(int hours, int minutes)
    {
        this.hours     = hours;
        this.minutes = minutes;
    }

    /**
     *
Set this object's time to be the same as the time of the object thatTime.
     *
     public void
acceptTime(Time thatTime)
    {
        this.hours     = thatTime.getHours();
        this.minutes = thatTime.
getMinutes();
    }

    public int getHours()
    {
        return hours;
    }

    public int getMinutes()
    {
        return minutes;
    }

    /**
     *
Set the time of the thatTime object to be the same as the time of this object.
     */
     public void
giveTime(Time thatTime)
    {
        // This method illustrates the use of the keywork this.
        thatTime.acceptTime(this);
    }

    public String toString( )
    {
        return  hours + ":" + minutes;
    }

    public static void main(String[] args)  
    {
        Time timeA = new Time(9, 30);
        Time timeB = new Time(8, 23);
        System.out.println("timeA   timeB");
        System.out.println("=====   =====");
        System.out.println(timeA + "    " + timeB);
        timeB.acceptTime(new Time(7, 45));
        System.out.println(timeA + "    " + timeB);
        timeB.giveTime(timeA);
        System.out.println(timeA + "    " + timeB);
    }
}

Running main() produces this result.

timeA   timeB
=====   =====
9:30      8:23
9:30      7:45

7:45      7:45

People sometime find the method giveTime() confusing. That method calls the method acceptTime() in another object. The potential confusion is that the two methods are defined in the same class, i.e., the Time class. So how can one object run the method giveTime() which asks a second object to run the method acceptTime() if both methods are in the same class?

The answer is that all Time objects have all the methods defined in the Time class. One way to think about it -- although this is not literally correct -- is to imagine that when you execute

Time timeA = new Time(9, 30);

the entire Time class is copied and given to timeA. Then when you execute 

Time timeB = new Time(8, 23);

the class is copied again and given to timeB.

So the line

        timeA.giveTime(timeB);

asks the timeA object to execute its giveTime() method.That method asks the timeB object to execute its acceptTime() method. Since each object has access to both methods, there is no problem.

 

Last edited by rabbott at 12:28 Oct 16, 2013.