Why are Java wrapper classes immutable?

前端 未结 9 1695
日久生厌
日久生厌 2020-12-02 17:25

I know the usual reasons that apply to general immutable classes, viz

  1. can not change as a side effect
  2. easy to reason about their state
  3. inhe
9条回答
  •  误落风尘
    2020-12-02 17:56

    For example, consider the following java program:

    class WhyMutable 
    {
        public static void main(String[] args) 
        {
            String name = "Vipin";
            Double sal = 60000.00;
            displayTax(name, sal);
        }
    
        static void displayTax(String name, Double num) {
            name = "Hello " + name.concat("!");
            num = num * 30 / 100;
            System.out.println(name + " You have to pay tax $" + num);
        }
    }
    
    Result: Hello Vipin! You have to pay tax $18000.0
    

    This is the case with pass by reference of wrapper class parameters as well. And, if strings and wrapper classes are non-final, anybody can extend those classes and write their own code to modify the wrapped primitive data. So, in order to maintain Data Integrity, the variables which we are using for data storage must be read-only,

    i.e., Strings and Wrapper classes must be final & immutable and “pass by reference” feature should not be provided.

提交回复
热议问题