Java
TOPIC 37 – CONSTRUCTORS II

AP EXTRA

 

 

AP LESSON NOTE

 

 

ABOUT THIS NOTE

In this note, we will look at more advanced examples of constructors that include the use of objects.

 

EXAMPLE

 

Consider this Point class:

 

     public class Point

     {

        public double x;

        public double y;

 

        public Point(double tmpx, double tmpy)

        {

            x = tmpx;   //setting x data field

            y = tmpy;   //setting y data field

        }

 

        public Point()

        {

            x = 0.0;

            y = 0.0;

        }

      }

 

We can add another constructor.  Let's consider a constructor that gets a Point object passed into it and uses that Point's x and y values to create our new Point.

 

 

          public Point(Point tmp)
          {

               x = tmp.x;

               y = tmp.y;

          }

 

This constructor may seem strange at first.  To create a Point using this constructor, one must first create the desired Point object.  So what's the point (see what I did there)?

Well, this constructor would provide us with the ability to clone a Point object.  It would allow us to make a copy of another Point.

 

The following code tests the new Point constructor:

 

public class Tester
{

     public static void main(String[] args)
     {

          //Using constructor #1
          Point p1 = new Point(3.4, 8.2);

          //Using constructor #2

          Point p2 = new Point(p1);

 

          System.out.println(p1.x + "," + p1.y);
          System.out.println(p2.x + "," + p2.y);

     }

}

 

It is important to note that p1 and p2 are two completely different objects.  Changing p1 will not change p2.