是个 '。'成员访问被认为是Java中的运算符?

时间:2012-01-31 22:57:47

标签: java operators

在Java中,我可以使用.访问类的公共成员,如下例中main方法的第二行所示(为了这个例子,忽略我对封装)。

public class Test {
    public static void main(String[] args) {
        Position p = new Position(0,0);
        int a = p.x; // example of member access
    }
}

class Position {
    public int x;
    public int y;

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

.是否被认为是Java编程语言中的运算符,就像*~!=被视为运算符一样?


修改 - 扩展上述示例:

正如已经指出的那样,似乎Java语言规范认为.是分隔符而不是运算符。然而,我想指出.展示的某些行为看起来似乎更像是操作者。考虑以上示例扩展到以下内容:

public class Test {
    public static void main(String[] args) {
        Position p = new Position(0,0);
        int a = p . x; // a -> 0
        int x = 1;
        int b = p . x + x; // b -> 1
    }
}

class Position {
    public int x;
    public int y;

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

很明显,正在执行某些优先级,以便在添加之前评估成员访问权限。这看起来很直观,因为如果首先评估添加,那么我们会p.2这是无意义的。然而,显然.表现出其他分离者没有的行为。

1 个答案:

答案 0 :(得分:15)

它被认为是分隔符,而不是运算符。请参阅Java Language Specification sections 3.11 and 3.12以获取所有分隔符和运算符的列表。

相关问题