【问题标题】:private instance and getter visibility in java [duplicate]java中的私有实例和getter可见性[重复]
【发布时间】:2013-08-28 16:02:15
【问题描述】:

感谢大家修复格式等,这里是全新的

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

为了计算一个 MyPoint 到另一个 MyPoint 的距离,我决定为 MyPoint another 使用 getter,因为 another 的 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;
    }
}

我认为由于 another 是一个 MyPoint 类并且实例 x 和 y 是私有的,因此 .x 和 .y 无法工作,这就是将实例设置为私有并使用吸气剂。

我错过了什么?

【问题讨论】:

    标签: java oop private getter


    【解决方案1】:

    private 表示只能从MyPoint 内访问字段。这并不意味着它们只能通过MyPoint同一个实例 访问。对于在“其他”实例上运行的方法,尤其是 equalscompareTo,访问同一类的其他实例中的私有状态是完全合法的。

    【讨论】:

    • so private 只阻止完全不同的类访问实例,但允许相同的类对象和方法访问,即使对象不同,只要它们属于同一个类。我做对了吗?谢谢!
    • 对。访问控制适用于类,而不是对象(实例)。
    猜你喜欢
    • 2010-09-23
    • 2013-07-26
    • 2015-01-21
    • 2016-02-21
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多