Java 中的增量运算符可以使用哪种操作数?

What kind of operands can you use with the increment operator in Java?

我不知道如果我对 Java 中的表达式应用递增运算符会发生什么。

int ai[] = new ai[10];
ai[0]++;

// ***

class Car {
  public int yearMade = 0;
}

class Person {
  public Car myCar = new Car();
}

Person p = new Person();
p.myCar.yearMade++;

你能按照第一个示例所示的方式递增数组的元素吗?

你能在 class 中增加一个字段吗(我知道封装和 getters/setters,我的问题是面向句法语义的)我在第二个例子中展示的方式?

我记得C/C++的年龄。例如,p -> x++ 曾经存在问题。使用递增或递减时,有时需要将复杂的表达式括在括号中。

感谢您的任何提示。

这两个问题的答案都是 "Yes, you can"。 p.myCar.yearMadeai[0] 都是变量 (an instance variable and a local variable, respectively),因此可以用作这四个运算符中任何一个的操作数。

4.12. Variables

A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type (§4.2) or a reference type (§4.3).

A variable's value is changed by an assignment (§15.26) or by a prefix or postfix ++ (increment) or -- (decrement) operator (§15.14.2, §15.14.3, §15.15.1, §15.15.2).

...

15.14.2. Postfix Increment Operator ++

At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.