分别编写两个类Point2D,Point3D来表示二维空间和三维空间的点,使之满足下列要求:

(1) Point2D有两个整型成员变量x, y (分别为二维空间的X,Y方向坐标)Point2D的构造方法要实现对其成员变量x, y的初始化。

(2)Point2D有一个void型成员方法offset(int a, int b),它可以实现Point2D的平移。

(3)Point3DPoint2D的直接子类,它有有三个整型成员变量x,y,z (分别为三维空间的X,Y,Z方向坐标)Point3D有两个构造方法:Point3D(int x,int y,int z)Point3D(Point2D p,int z),两者均可实现对Point3D的成员变量x, y,z的初始化。

(4)Point3D有一个void型成员方法offset(int a, int b,int c),该方法可以实现Point3D的平移。

(5)一个测试类中的主函数main()中实例化两个Point2D的对象p2d1p2d2,打印出它们之间的距离,再实例化两个Point3D的对象p3d1p3d2,打印出他们之间的距离。

2D与3D既是独立又是继承关系.

主要用到:1.数学函数求两点之间的距离2.super的用法3.类的继承4.对象作函数参数

以下通过代码具体分析

 1 import java.lang.Math;
 2 class Point2D{
 3 protected int x,y;        //保护类成员主要用于继承
 4 Point2D(){
 5 }
 6 Point2D(int x,int y){       //有参构造方法
 7 this.x = x;
 8 this.y = y;
 9 }
10 public int getX(){
11 return x;
12 }
13 public int getY(){        //方便在其他类中使用该类中的私有成员变量
14 return y;
15 }
16 public void offset(int a,int b){      //偏移后的横纵坐标值
17 this.x += a;
18 this.y += b;
19 }
20 public void show(){        //show横纵坐标
21 System.out.println("坐标为:["+x+ "," +y +"]");
22 }
23 }
24 class Point3D extends Point2D{  //类的继承
25 private int z;           //第三点x
26 Point3D(){
27 }
28 Point3D(int x,int y,int z){      //有参构造方法三点分别初始化
29 super(2,3);            //调用父类的有两个参数的构造方法
30 this.z= z;
31 }
32 public int getZ(){
33 return z;
34 }
35 Point3D(Point2D p,int z){     //有参构造方法,以对象作形参.用p对象调用get方法以初始化继承的私有成员变量
36 super(p.getX(),p.getY());
37 this.z=z;
38 }
39 public void offset(int a,int b,int c){  //3D的偏移量
40 super.offset(a,b);         //方法同上,调用父类的偏移方法
41 z=z+c;
42 }
43 public void show(){        //show3D坐标值
44 System.out.println("坐标为:["+x+ "," +y + "," + z +"]");
45 }
46 }
47 public class Test3_1 {
48 public static void main(String[] args){
49 Point2D p2d1=new Point2D(2,3);
50 Point2D p2d2=new Point2D(3,4);     //初始化2D两点p2d1,p2d2
51 double retDistance2D=distance2D(p2d1,p2d2);
52 System.out.println(retDistance2D);    //输出2D两点之间距离
53 Point3D p3d1=new Point3D(2,3,4);
54 Point3D p3d2=new Point3D(3,4,5);
55 double retDistance3D=distance3D(p3d1,p3d2);
56 System.out.println(retDistance3D);    //同上面的2D
57 }
58 public static double distance2D(Point2D p2d1,Point2D p2d2){//对象作形参
59 double distance;
60 double distanceX;
61 double distanceY;
62 distanceX=Math.pow((p2d1.getX()-p2d2.getX()),2);//(x1-x2)2=X
63 distanceY=Math.pow((p2d1.getY()-p2d2.getY()),2);//(y1-y2)2=Y
64 distance=Math.sqrt(distanceY+distanceX);//X+Y再开方
65 return distance;
66 
67 }
68 public static double distance3D(Point3D p3d1,Point3D p3d2){//同2D方法一致
69 double distance;
70 double distanceX;
71 double distanceY;
72 double distanceZ;
73 distanceX=Math.pow((p3d1.getX()-p3d2.getX()),2);
74 distanceY=Math.pow((p3d1.getY()-p3d2.getY()),2);
75 distanceZ=Math.pow((p3d1.getZ()-p3d2.getZ()),2);
76 distance=Math.sqrt(distanceY+distanceX+distanceZ);
77 return distance;
78 
79 }
80 }

 

posted @ 2017-11-05 09:30  WETYUIOASHZXCVBNM  阅读(4919)  评论(0编辑  收藏  举报