Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Point3D: A client or a subclass of Point2D?


The new Point3D class is here

using System;

public class Point3D {

  private Point2D point2DPart;
  private double z;

  public Point3D(double x, double y, double z){
   point2DPart = new Point2D(x,y);
   this.z = z;
  }

  public double X{
    get {return point2DPart.X;}
  }

  public double Y{
    get {return point2DPart.Y;}
  }

  public double Z{
    get {return z;}
  }

  public void Move(double dx, double dy, double dz){
    point2DPart.Move(dx, dy);
    z += dz;
  }

  public override string ToString(){
    return "Point3D: " + "(" + X + ", " + Y + ", " + Z + ")" + ".";
  }
}

When the following client program runs

using System;

public class Application{

  public static void Main(){
    Point2D p1 = new Point2D(1.1, 2.2),
            p2 = new Point2D(3.3, 4.4);

    Point3D q1 = new Point3D(1.1, 2.2, 3.3),
            q2 = new Point3D(4.4, 5.5, 6.6);

    p2.Move(1.0, 2.0);
    q2.Move(1.0, 2.0, 3.0);
    Console.WriteLine("{0} {1}", p1, p2);
    Console.WriteLine("{0} {1}", q1, q2);
  }

}

the output is

Point2D: (1,1, 2,2). Point2D: (4,3, 6,4).
Point3D: (1,1, 2,2, 3,3). Point3D: (5,4, 7,5, 9,6).

which is identical to the output from the accompanying slide.

It requires a bit more work to implement Point3D by aggregation instead of by extension of class Point2D.