Experiment 1: Use of Java development environment and object-oriented programming

  1. Write two classes Point2D and Point3D respectively to represent points in two-dimensional space and three-dimensional space to meet the following requirements:
  1. Point2D has two integer member variables x, y (respectively the coordinates in the X and Y directions of the two-dimensional space). The construction method of Point2D must implement the initialization of its member variables x, y.

  2. Point2D has a void type member method offset(int a, int b), which can realize the translation of Point2D.

  3. Point3D is a direct subclass of Point2D, it has three integer member variables x, y, z (respectively the X, Y, Z direction coordinates of the three-dimensional space), Point3D has two construction methods: Point3D (int x, int y , int z) and Point3D(Point2D
    p, int z), both can realize
    the initialization of the member variables x, y, z of Point3D .

  4. Point3D has a void type member method offset(int a, int b, int c), which can realize the translation of Point3D.

  5. In the main function main() of Point3D, instantiate two Point2D objects p2d1, p2d2, print the distance between them, and then instantiate two Point2D objects p3d1, p3d2, and print the distance between them.

package test;
public class Point2D {
 int x;
 int y;
 Point2D(int _x,int _y){
  x=_x;
  y=_y;
 }
 public void offset(int a,int b) {
  x+=a;
  y+=b;
 }
}
package test;
public class Point3D extends Point2D{
 int z;
 Point3D(int _x, int _y,int _z) {
  super(_x, _y);
  z=_z;
 }
 Point3D(Point2D p,int _z){
  super(p.x,p.y);
  z=_z;
 }
 public void offset(int a,int b,int c) {
  x+=a;
  y+=b;
  z+=c;
 }
 public static void main(String[] args) {
  Point2D p2d1=new Point2D(1,4);
  Point2D p2d2=new Point2D(2,5);
  System.out.println(Math.sqrt(Math.pow((p2d1.x-p2d2.x),2)+Math.pow((p2d1.y-p2d2.y),2)));
  Point3D p3d1=new Point3D(1,4,8);
  Point3D p3d2=new Point3D(2,5,9);
  System.out.println(Math.sqrt(Math.pow((p3d1.x-p3d2.x),2)+Math.pow((p3d1.y-p3d2.y),2)+Math.pow((p3d1.z-p3d2.z),2)));
 }
}

Guess you like

Origin blog.csdn.net/Warmmm/article/details/106984677