比较类属性

时间:2016-07-24 09:18:04

标签: java class

我想编写一个方法来比较同一个类中两个对象的属性。说我得到了point1& Point类的point2,其属性为:

public class Point{
    private double x;
    private double y;
    private double z;

[...] */constructor and methods*/[...]
}

public static void main (String[] args){
    Point point1 = new Point(5, 10, 20);
    Point point2 = new Point(0, 5, 10); 
}

我想比较point1&的x,y和z值。 point2互相攻击,但我不知道该怎么做。如何区分方法代码块中的不同值?如果可以的话,这是我要写的理论方法:

public double comparePoints(Point a, Point b){
    if (x1 < x2){
        System.out.println("Point b has the bigger x-value");
        return x2;
    }
    etc.
}

任何想法如何做到这一点?

2 个答案:

答案 0 :(得分:0)

如果你想获得on对象的一个​​属性,你有两个选择:

1 /使用getter方法:        a.getAttributeX(Point){...}

2 /一旦创建一个对象Point你就可以使用它:       if(a.x&lt; b.x)then ....

PS:使用getter方法总是安全的!

答案 1 :(得分:0)

您已经对问题有了很好的答案,即使用比较器接口进行比较,使用getter \ setter在声明为私有时安全地访问属性,或者使用obj1.x和obj2从每个对象访问属性。 X。这取决于你想要采取什么方法的确切要求。我更新的以下代码片段对两个对象的属性进行了基本比较。

public class Point {    

        private double x;
        private double y;
        private double z;    

        //Constructor
        Point(double l,double m,double n){

            this.x = l;
            this.y = m;
            this.z = n;         

        }

    //main method
    public static void main (String[] args){

        Point point1 = new Point(5, 10, 20);

        Point point2 = new Point(0, 5, 10); 

       //Object that is created with the greater value
        Point point3 = comparePoints(point1,point2);

        System.out.println("-----The greater value of property, "
                + "between the two compared objects is as below----");

        System.out.println("x ="+point3.x);
        System.out.println("y ="+point3.y);
        System.out.println("z ="+point3.z);

    }


    //Compare method declared static, for the satic main method to access
    public static Point comparePoints(Point a, Point b){    

        System.out.println("Values in Object a = "+a.x+""+a.y+""+a.z);

        System.out.println("Values in Object a = "+b.x+""+b.y+""+b.z);

        System.out.println("Point a has the bigger x-value");

        Point h = new Point(0,0,0);     

        if (a.x < b.x){
            h.x = b.x;
        }
        else{
            System.out.println("Point a has the bigger x-value");
            h.x = a.x;
        }

        if (a.y < b.y){
            System.out.println("Point b has the bigger y-value");
            h.y = b.y;
        }
        else{
            System.out.println("Point a has the bigger y-value");
            h.y = a.y;
        }

        if (a.z < b.z){
            System.out.println("Point b has the bigger z-value"+b.z);
            h.z = b.z;
        }
        else{
            System.out.println("Point a has the bigger z-value"+a.z);
            h.z = a.z;
           }

        return h;

    }

}