java中的私有实例和getter可见性

时间:2013-08-26 08:07:06

标签: java oop private getter

并感谢大家修复格式等,全新的

我最近开始学习java,在一次练习中我遇到了一个问题,抱歉,如果我错过了发布规则:

计算从一个MyPoint到另一个Mypoint的距离,我决定使用MyPoint 另一个的getter,因为另一个的x和y应该是私有的,不能是用于点操作(another.x another.y);

public class MyPoint {
    private int x;
    private int y;                   

    public int getX() {             
        return x;
    }

    public int getY() {            
        return y;
    } 

    public double distance(MyPoint another) { 
        int xDiff = this.x - another.getX();           //getter
        int yDiff = this.y - another.getY();          // getter

        return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
    }
}

public class TestMyPoint {
    public static void main(String[] args) {
        MyPoint a = new MyPoint(3,0);
        MyPoint b = new MyPoint(0,4);

        System.out.println(a.distance(b));  // this works fine;
    }
}

然而,如果我回到代码并将another.getX()更改为another.x,代码仍然有效。和y相同。

public class MyPoint {
    private int x;
    private int y;              

    public MyPoint(int x, int y) {
        this.x = x;
        this.y = y;
    }     

    public int getX() {             
        return x;
    }
    public int getY() {            
        return y;
    } 

    public double distance(MyPoint another) { 
        int xDiff = this.x - another.x;                         //no getter
        int yDiff = this.y - another.y;                         //no getter

        return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
    }
}


public class TestMyPoint {
    public static void main(String[] args) {
        MyPoint a = new MyPoint(3,0);
        MyPoint b = new MyPoint(0,4);

        System.out.println(a.distance(b));  // this still works fine;
    }
}

我认为,因为另一个是一个MyPoint类,而实例x和y是私有的,所以.x和.y无法工作,这就是将实例设置为私有并使用吸气剂。

我错过了什么?

1 个答案:

答案 0 :(得分:7)

private表示只能在MyPoint内访问这些字段。这并不意味着只能使用{em> MyPoint相同实例来访问它们。对于在“其他”实例上运行的方法(尤其是equalscompareTo)来访问同一类的其他实例中的私有状态,这是完全合法的。