What is meant by immutable?

后端 未结 17 1617
天命终不由人
天命终不由人 2020-11-22 02:27

This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie.

  1. Can somebody clarify what is meant by immutable? <
17条回答
  •  无人及你
    2020-11-22 03:08

    java.time

    It might be a bit late but in order to understand what an immutable object is, consider the following example from the new Java 8 Date and Time API (java.time). As you probably know all date objects from Java 8 are immutable so in the following example

    LocalDate date = LocalDate.of(2014, 3, 18); 
    date.plusYears(2);
    System.out.println(date);
    

    Output:

    2014-03-18

    This prints the same year as the initial date because the plusYears(2) returns a new object so the old date is still unchanged because it's an immutable object. Once created you cannot further modify it and the date variable still points to it.

    So, that code example should capture and use the new object instantiated and returned by that call to plusYears.

    LocalDate date = LocalDate.of(2014, 3, 18); 
    LocalDate dateAfterTwoYears = date.plusYears(2);
    

    date.toString()… 2014-03-18

    dateAfterTwoYears.toString()… 2016-03-18

提交回复
热议问题