Are all final class immutable?

前端 未结 8 2314
一生所求
一生所求 2021-02-19 09:34

Are all final classes in Java immutable. String and Integer both are final classes and both are immutable i beleive.

8条回答
  •  甜味超标
    2021-02-19 10:01

    A final immutable classes cannot be mutated. Here below it shows a non-final immutable class being mutated:

    // a class not intended to be mutated 
    public class GoodClass{
    
       private String name;
    
       public GoodClass() {
           this.name = "Good Class Neme";
       }
    
       public String getName() {
           return name;
       }
    }
    
    public class BadClass extends GoodClass {
    
       private String name;
    
       public String getName() {
           return name;
       }
    
       // mutating state
       public void setName(String name) {
           this.name = name;
       }
    }
    
    
    
    

提交回复
热议问题