More about Objects and Classes

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: More about Objects and Classes
Printed by: Guest user
Date: Thursday, July 7, 2022, 1:43 PM

Description

The relational operations on primitive data are ==, >=, <=, >, <, and !=. They compare two data values, when those values' type has an ordering. For example, integers are ordered by size or magnitude. The result of a relational operation is a boolean value: either True or False. The relational operators on objects like Strings are different, and they are expressed as methods. Pay special attention to the equality method, equals().

1. More about Objects and Classes

This chapter reinforces the topics introduced in the last two chapters, and discusses several new topics.

The Point class is convenient for discussing these topics. But it is not a class that Advanced Placement students are expected to know and outside of this chapter and the next these notes do not use it again.

You have seen some of the material in this chapter before. But, don't rush through it. The purpose of this chapter is to review topics that you may still be somewhat unclear about.

Chapter Topics:

      • The Point class
      • Class descriptions
      • The toString() method
      • Changing the data in an object vs constructing a new object
      • The equals() method
      • The == operator (again)
      • Aliases

Question 1:

In geometry, what is a two dimensional point?

Source: Bradley Kjell, http://programmedlessons.org/Java9/chap42/ch42_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.

2. The Class Point


Answer:

A 2D geometrical point gives a location using two values, usually an x value and a y value.

The Class Point

twoDgrid


Think of a two dimensional point as an object that consists of two values, the distance x from the origin along a horizontal axis, and the distance y from the origin along a vertical axis. In Java graphics, the upper left corner of a drawing area (such as a window) is considered to be the origin (0, 0), so y increases going downward.

It is convenient to think of a point as a single thing (not as two separate things). For example, you think of the end point of a line as one thing. And you think of the corner of a square as one thing. This is an example of abstraction. In Java, an abstraction usually calls for a class.

Java comes with a package of predefined classes that are used for building graphical user interfaces, the Application Windowing Toolkit, or the AWT. One of the many classes in the AWT is the class Point.

The class Point describes two things: the variables (the data) and the methods (the behavior) of Point objects.


Question 2:

What two variables do you expect a Point object to have?

Click here for a 

3. Description of a Class


Answer:

A point consists of a pair of numbers, (x, y).

Description of a Class

The Java documentation describes the class Point. Look at the documentation on the web to see it. Point (Do a Google search for "Java Point" if the link fails). You will see something like the following:

The documentation shows the data and methods contained in Point objects, the constructors that create such objects, and their methods. Variables are sometimes called fields (as is done here). The two variables are named x and y and are of type in

java.awt
Class Point . . . // Field Summary
int x;
int y; // Constructor Summary
Point(); // creates a point at (0,0)
Point(int x, int y); // creates a point at (x,y)
Point( Point pt ); // creates a point at the location given in pt // Method Summary
boolean equals(Object obj); // checks if two point objects hold equivalent data
void move(int x, int y); // changes the (x,y) data of a point object
String toString(); // returns character data that can be printed (I've left out some methods we won't be using.)

Question 3:

There are three constructors listed for Point. Each one creates the same type of object.
What is the difference between the constructors?

4. Multiple Constructors


Answer:

The different constructors require different parameters. 
(Different types of data are supplied to the constructors.)

Multiple Constructors

import java.awt.*;      // import the package that contains Point
class PointEg1
{

  public static void main ( String arg[] )
  {
    Point a, b, c;              // reference variables

    a = new Point();            // create a Point at (0,  0); 
                                // save the reference in "a"
    b = new Point( 12, 45 );    // create a Point at (12, 45); 
                                // save the reference in "b"
    c = new Point( b );         // create a Point containing data equivalent
                                // to the data referenced by "b"
  }
}   

Any of the three constructors can be used to create a Point. It is a matter of convenience which constructor you use. Look at the example program.

To use the definition of class Point, import the package that contains it. The statement:

import java.awt.*

says to use the AWT package that comes with Java. The * says that everything defined in the package can be used (although this program only uses the Point class).


Question 4:

Say that the program has just been loaded into main memory and is just about to start running.

How many reference variables are there?

How many objects are there?

5. Instantiating the Point Objects


Answer:

Say that the program has just been loaded and is just about to start running.

How many reference variables are there?    3

How many objects are there?    Zero

Instantiating the Point Objects

refsABC

Here is a picture of the variables just as the program starts running. No objects have been instantiated yet, so the reference variables ab, and c do not refer to any objects. To emphasize this, a slash has been put through the box for each variable.

import java.awt.*;
class PointEg1
{

  public static void main ( String arg[] )
  {
    Point a, b, c;              // reference variables

    a = new Point();            // create a Point at (0, 0); 
                                // save the reference in "a"
    b = new Point( 12, 45 );    // create a Point at (12, 45); 
                                // save the reference in "b"
    c = new Point( b );         // create a Point containing data equivalent
                                // to the data referenced by "b"
  }
}          

The program:

  1. Declares three reference variables ab, and c, which can hold references to objects of type Point.
  2. Instantiates a Point object with x=0 and y=0.
    (The documentation tells us that a constructor without parameters initializes x and y to zero.)
  3. Saves the reference to the object in the variable a.
  4. Instantiates a Point object with x=12 and y=45.
  5. Saves the reference to the object in the variable b.
  6. Instantiates a third Point object that is similar to the second.
  7. Saves the reference in the variable c.

Once each Point object is instantiated, it is the same as any other (except for the particular values in the data). It does not matter which constructor was used to instantiate it.


Question 5:

What are the values of x and y in the third point?

6. Picture of the Objects


Answer:

x = 12 and y = 45.

Picture of the Objects

objectsABC

The Points were constructed with the statements

    a = new Point();
    b = new Point( 12, 45 ); 
    c = new Point( b );

The constructor for point a automatically uses (0, 0).

The constructor for point b uses data from its two parameters.

The constructor for point c is given a reference to another point. The x and y values of the new point c will take their values from b as explained in the Point, class documentation.

After the three objects have been created (just before the program closes) the situation looks like the picture.

Each reference variable refers to an object. Each object contains its own data and its own methods.


Question 6:

Look at the picture. Is it clear what the phrase "the object a" means?

7. The toString() Method


Answer:

Yes, even though the phrase is a little bit deceptive. One should really say
"the object currently referenced by a," or "the object referred to by a," or "the object a points to,"
but usually people say "the object a" and expect you to know what they mean.

The toString() Method

The example program does very little that is visible on the monitor screen. It would be nice to print something out. The bytes that make up an object cannot be sent directly to the monitor because they are not ASCII character data. For example, the two ints of a Point use a data type that can't be sent directly to a monitor. Of course, the methods of an object are in Java bytecode, which makes no sense to a monitor, either.

Luckily, there is a method defined in class Point that can be used to create a printable String for a Point object. Point, class

The toString() method of a Point object creates a String object, which can then be printed. Look at the documentation:

  public String toString();   // returns character data that can be printed
      |      |        |
      |      |        +--- this is the method name.  It takes no parameters.
      |      |
      |      +--- this says that the method returns a String object
      |
      +--- anywhere you have a Point object, you can use this method

All objects have their own toString() method, so it is possible to print out something for any object your program has created. (Often, though, the String is not very useful.)

Question 7:

(Review: ) What is a parameter?

8. Program that uses the toString() Method


Answer:

parameter is an item of data supplied to a method or a constructor.

Program that uses the toString() Method

import java.awt.*;
class PointEg2
{
  public static void main ( String arg[] )
  {
    Point a, b, c;              // reference variables

    a = new Point();            // create a Point at ( 0,  0); 
                                // save the reference in "a"
    b = new Point( 12, 45 );    // create a Point at (12, 45); 
                                // save the reference in "b"
    c = new Point( b );         // create a Point

    String strA = a.toString(); // create a String object based on the data
                                // found in the object referenced by "a".
    System.out.println( strA );
  }
}

toString() needs no parameters. However, use empty parentheses when the method is called. The example program shows this.

When this program runs, the statement:

String strA = a.toString(); 

creates a String object based on the data in the object referred to by a. The strA refers to this new String object. Then the characters from the String are sent to the monitor with println.

The program prints out:

java.awt.Point[x=0,y=0]

The Point object has not been altered: it still exists and is referred to by a.


Question 8:

Just as the program is about to end, how many objects have been created? Has any garbage been created?

9. Using a Temporary Object


Answer:

Just as the program is about to close, how many objects have been created?     Four, counting the String object.

Has any garbage been created?    No, because a reference variable points to each object.

Using a Temporary Object


Here is another modification to the example program:

import java.awt.*;
class PointEg3
{

  public static void main ( String arg[] )
  {
    Point a = new Point();              // declarations and construction combined 
    Point b = new Point( 12, 45 );    
    Point c = new Point( b );

    System.out.println( a.toString() ); // create a temporary String based on "a"
  }
}

This program creates three Points with the same values as before, but now the declaration and construction of each point is combined.

The last statement has the same effect as the last two statements of the previous program:

  1. When the statement executes, a refers to an object with data (0,0).
  2. The toString() method of that object is called.
  3. The toString() method creates a String object and returns a reference to it.
  4. At this point of the execution, you can think of the statement like this:
    System.out.println( reference to a String );
  5. The println method of System.out uses the reference to find the data to print out on the monitor.
  6. The statement finishes execution; the reference to the String has not been saved anywhere.

Since no reference was saved in a reference variable, there is no way to find the String object after the println finishes. The String object is now garbage. That is OK. It was only needed for one purpose, and that purpose is completed. Using objects in this manner is very common.


Question 9:

What type of parameter (stuff inside parentheses) does the System.out.println() method expect?

10. It expects a reference to a String as a parameter.


Answer:

Just as the program is about to close, how many objects have been created?     Four, counting the String object.

Has any garbage been created?    No, because a reference variable points to each object.

Automatic Call of toString()


It looks like the following will not work:

Point a = new Point();  // a is a Point reference

System.out.println( a ); 
                    |
                    +--- should be String reference


However, it does work, for the following reason:

When a parameter should be a String reference, but is a reference to another type of object, Java calls the object's toString() method to create a String and then uses the resulting String reference.

All objects (of any type at all) have their own toString() method, so this trick works with any object.


Question 10:

(Puzzle: ) Does a String object have a toString() method?

11. Example Program Extended


Answer:

Yes. The method just returns a reference to the String itself. No new object is created.

Example Program Extended

          
import java.awt.*;
class PointEg3
{

  public static void main ( String arg[] )
  {
    Point a = new Point();              // declarations and construction combined
    Point b = new Point( 12, 45 );
    Point c = new Point( b );

    System.out.println( a ); // create a temporary String based on "a", print it out
    System.out.println( b ); // create a temporary String based on "b", print it out
    System.out.println( c ); // create a temporary String based on "c", print it out
  }
}            


The example program has been changed, yet again. The program prints out:

java.awt.Point[x=0,y=0]
java.awt.Point[x=12,y=45]
java.awt.Point[x=12,y=45]

This program is deceptively short. However, its execution calls for quite a bit of activity.


Question 11:

Just as the program is about to close, how many objects have been created?

How many object references are there?

Has any garbage been created?

12. Changing Data inside a Point


Answer:

  • Just as the program is about to close, how many objects have been created ?

        Six — three Point objects and three temporary String objects
  • How many object references are there?
        Three — each referencing a Point
  • Has any garbage been created?
        Three objects — each temporary String object

Changing Data inside a Point

Look again at the description of class Point, class Point. One of the methods is:

public void move( int x, int y ) ;

This method is used to change the x and the y data inside a Point object. The modifier public means that it can be used anywhere in your program; void means that it does not return a value.

This part of the description

( int x, int y )

says that when you use move, you need to supply two int parameters that give the new location of the point.

Here is the example program, modified again:


import java.awt.*;
class PointEg4
{

  public static void main ( String arg[] )
  {
    Point pt = new Point( 12, 45 );   // construct a Point
    System.out.println( pt );     

    pt.move( -13, 49 ) ;              // change the x and y in the Point
    System.out.println( pt ); 

  }
}

Here is what it writes to the screen:

java.awt.Point[x=12,y=45]
java.awt.Point[x=-13,y=49]

Question 12:

How many Point objects are created by this program?

How many temporary String objects are created by this program?

13. One Object, with Changing Data


Answer:

How many Point objects are created by this program?
    One — the object referenced by pt

How many temporary String objects are created by this program?
    Two — one temporary String object for each println()

One Object, with Changing Data

objectsBeforeAfter

The program changes the data inside a Point object using that object's move() method:

import java.awt.*;
class PointEg4
{
  public static void main ( String arg[] )
  {
    Point pt = new Point( 12, 45 );  // construct a Point
    System.out.println( pt );     

    pt.move( -13, 49 ) ;             // change the x and y in the Point
    System.out.println( pt ); 
  }
}       

Question 13:

Can a constructor be used to change the data inside an object?

14. Dangerously Similar Program


Answer:

No. Constructors always create new objects. (They might get data from an old object,
but a completely separate object will be constructed using a different chunk of main memory.)

Dangerously Similar Program

objectsBeforeAfter2

The example program has been modified to create a second Point object.

In the "After" picture, the first object is shaded to emphasis that it is now "garbage." The reference variable pt now refers to the newly created object.

import java.awt.*;
class ChangingData2
{
  public static void main ( String arg[] )
  {
    Point pt = new Point( 12, 45 );            // construct a Point
    System.out.println( pt );     

    pt = new Point( -13, 49 ) ;                // construct a new Point
    System.out.println( pt ); 
  }
}  

Question 14:

What will this second version of the program output to the monitor?

15. Review


Answer:

Exactly the same as the first version of it:

    java.awt.Point[x=12,y=45] java.awt.Point[x=-13,y=49]

You can not be sure about the internal workings of a program by inspecting its output!

Review

You might want to review the two programs to be sure that you understand their differences:

Program:What it did:
object, method changes state The first programAn object was constructed. The variable pt refers it.
Then, new data replaced the old data inside the same object.
object, assignment replaces old The second programAn object was constructed. The variable pt refers it.
Then, a new object was constructed with new data, and pt was changed
to refer to the new object. The first object became garbage.

Question 15:

When are two points equivalent?

16. The equals() Method


Answer:

The x value and the y value of one point is equal to the x value and the y value of the other point.

The equals() Method

The equals() method is defined for class Point:

pointA.equals( pointB )   —— returns true if the two points
                             contain equivalent data

The example program shows this:

import java.awt.*;
class EqualsDemo
{
  public static void main ( String arg[] )
  {
    Point pointA = new Point( 7, 99 );    // first Point
    Point pointB = new Point( 7, 99 );    // second Point with equivalent data

    if ( pointA.equals( pointB ) )
      System.out.println( "The two objects contain the same data: " + pointA );
    else
      System.out.println( "The two objects are not equivalent: " + pointA + 
          " differs from" + pointB);     

  }
}


Question 16:

What is the output of this program? (You might wish to copy-paste-and-run
this program to check your answer.)

17. Different Objects, Equivalent Data


Answer:

The two objects contain the same data: java.awt.Point[x=7,y=99]

Different Objects, Equivalent Data

twoSameData

The picture shows the situation. There are two distinct objects (each constructed out of different bytes of memory).

The equals() method returns true because the data is equivalent.


Question 17:

Would the == operator do the same as the equals() method?

18. Testing Two Reference Variables


Answer:

No. The == operator tests if two reference variables refer to the same object.

Testing Two Reference Variables

twoSameData

Here is the program, modified to use the == operator.

The objects are the same as before so the picture is the same as on the previous page.


import java.awt.*;
class EqualsDemo2
{
  public static void main ( String arg[] )
  {
    Point pointA = new Point( 7, 99 );   // first Point
    Point pointB = new Point( 7, 99 );   // second Point with equivalent data

    if ( pointA == pointB  )
      System.out.println( "The two variables refer to the same object" );   
    else
      System.out.println( "The two variables refer to different objects" );  

  }
}

The == operator looks at the references in the two reference variables to see if those reverences are identical.

Question 18:

What is the output of this program?

19. Alias


Answer:

The two variables refer to different objects

Alias

Here is a further modified program:


import java.awt.*;
class EqualsDemo3
{
  public static void main ( String arg[] )
  {
    Point pointA = new Point( 7, 99 );     // pointA refers to a Point Object
    Point pointB = pointA;                 // pointB refers to the same Object 

    if ( pointA == pointB  )
      System.out.println( "The two variables refer to the same object" );     
    else
      System.out.println( "The two variables refer to different objects" );     

  }
}   

It is possible to have two (or more) reference variables refer to the same object. The modification to the program that does that.

Only one object has been created (because there is only one new operator.) The second statement:

Point pointB = pointA; 

copies the reference that is in pointA into the reference variable pointB.

Now both reference variables point to the same object.

alias: When two or more reference variables refer to the same object, each variable is said to be an alias.

Question 19:

What is the output of the program?

20. alias-detector


Answer:

The two variables refer to the same object

alias-detector

aliasEg

The == operator looks only at variables. If two variables contain a reference to the same object, the operator evaluates to true.

Think of the == operator as an alias-detector.


Question 20:

(Thought question:) Could the equals() method be used with aliases?

21. Equivalence of Aliases


Answer:

Yes. You have to be careful how you use the result, however.

alias-detector

aliasEg

Here is the example program (again!) with this modification:

import java.awt.*;
class EqualsDemo4
{
  public static void main ( String arg[] )
  {
    Point pointA = new Point( 7, 99 );     // pointA refers to a Point Object
    Point pointB = pointA;                 // pointB refers to the same Object 

    if ( pointA.equals( pointB ) )
    {
      System.out.println( "The two variables refer to the same object," );
      System.out.println( "or different objects with equivalent data." );
    }
    else
      System.out.println( "The two variables refer to different objects" );     

  }
}


The picture of the situation is the same as before. But now the equals() method is used. It:

  1. Uses the reference pointA to get the x and y from the object.
  2. Uses the reference pointB to get the x and y from the same object.
  3. Determines that the two x's are the same and that the two y's are the same.
  4. Returns a true.

The fact that the object is the same object in step 1 and step 2 does not matter. The x's that are tested are the same, and the y's that are tested are the same, so the result is true.


Question 21:

If the == operator returns a true will the equals() method return a true, always?

22. Summary


Answer:

Yes. 

Summary

The following table is a summary. There are four rows, one for each choice of true and false. The last row shows a choice that is not possible. If == is true, there is only one object, which must be equals to itself.


code sectionpointA == pointBpointA.equals( pointB )
Point pointA = new Point( 21, 17 );
Point pointB = pointA;
truetrue
Point pointA = new Point( 21, 17 );
Point pointB = new Point( -99, 86 );
falsefalse
Point pointA = new Point( 21, 17 );
Point pointB = new Point( 21, 17 );
falsetrue
Not Possible
truefalse


Question 22:

Does pointA.equals(pointB) return the same true/false value as pointB.equals(pointA) ?

Does pointA == pointB return the same true/false value as pointB == pointA ?

23. Practice


Answer:

Does pointA.equals(pointB) return the same true/false value as pointB.equals(pointA) ?

    Yes.

Does pointA == pointB return the same true/false value as pointB == pointA ?

    Yes.

Practice

Perhaps you would like to practice? Assume that each row is independent of the others.


code sectionpointA == pointBpointA.equals( pointB )
Point pointA = new Point( 0, 0 );
Point pointB = new Point( 0, 0 );
Point pointA = new Point( 21, 17 );
Point pointB = pointA;
Point pointA = new Point( 21, 17 );
Point pointB = new Point( 7*3, 20-3 );
Point pointA = new Point( 21, 17 );
Point pointB = new Point( pointA );
Point pointA = new Point( 21, 17 );
Point pointB = new Point( 21, 17 );
pointA.move( 8, 12 );
Point pointA = new Point( 21, 17 );
Point pointB = pointA;
pointB.move( 8, 12 );

Notice that in the last question there is only one object, with two variables pointing to it. When the move() operation is performed, the data in that one object is changed. So it is still true that the data referred to by one reference variable is the same as that referred to by the the other. So equals() still reports true.

With aliases it is easy to get confused and think that there are two objects when in fact there is only one. Perhaps this is why bank robbers use aliases.



Question 23:

Could an object have more than two aliases?

24. Fun Activity!


Answer:

Yes. See some of the questions below.

    Fun Activity!

    (otherwise known as more practice)

    Assume that each row is independent of the others.

    code sectionpointA == pointBpointA.equals( pointB )pointB == pointCpointB.equals( pointC )
    Point pointA = new Point( 0, 0 );
    Point pointB = new Point( 0, 0 );
    Point pointC = new Point( 0, 0 );
    
    Point pointA = new Point( 13, -15 );
    Point pointB = pointA;
    Point pointC = pointA;
    
    Point pointA = new Point( 13, -15 );
    Point pointB = pointA;
    Point pointC = pointB;
    
    Point pointA = new Point( 13, -15 );
    Point pointB = pointA;
    Point pointC = new Point( 13, -15 );
    
    Point pointA = new Point( 13, -15 );
    Point pointB = pointA;
    Point pointC = pointB;
    pointA.move( 8, 12 );
    
    Point pointA = new Point( 13, -15 );
    Point pointB = pointA;
    Point pointC = new Point( 13, -15 );
    pointA.move( 8, 12 );
    

    Question 24:

    Do you imagine that professional programmers ever get == and equals confused?

    25. End of the Chapter

    
    

    Answer:

    Yes. It happens all the time. Does that mean you are equal to them or == to them?

      End of the Chapter

      You have reached the end of the chapter. If you missed some points, click on a subject that interests you to go to where it was discussed.