Search code examples
oopencapsulation

Are custom classes in Java mutable by default?


I've been reading up on encapsulation and was wondering; if I make a new class, is it by default mutable? If so, how would I go about making it an immutable class, if possible, without just doing defensive copying?

Thanks.


Solution

  • It depends on what you put in the class.

    public class MutableClass {
        private String firstName;
    
        public MutableClass(String s) {
            firstName = s;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        // this allows mutation...
        public void setFirstName(String s) {
            firstName = s;
        }
    }    
    
    public class ImmutableClass {
        private String firstName;
    
        public MutableClass(String s) {
            firstName = s;
        }
    
        public String getFirstName() {
            return firstName;
        }
    }
    

    That doesn't account of things like setAccessible with reflection, but I expect that is not what you are concerned about.

    I hope that helps.