Implement a final class without the “final” keyword

后端 未结 7 1720
生来不讨喜
生来不讨喜 2020-12-29 10:53

A friend of mine was asked that question in his on-phone job interview a couple of days a go. I don\'t have a clue. can anyone suggest a solution? (His job interview is ov

7条回答
  •  庸人自扰
    2020-12-29 11:19

    You can make your class immutable without using final keyword as:

    1. Make instance variable as private.
    2. Make constructor private.
    3. Create a factory method which will return the instance of this class.

    I am providing immutable class here in Java.

    class Immutable {
        private int i;
        private Immutable(int i){
         this.i = i;
        }
        public static Immutable createInstance(int i){
             return new Immutable(i);
        }
        public int getI(){return i;}
    }
     class Main {
        public static void main(string args[]){
           Immutable obj = Immutable.createInstance(5);
        }
    }
    

提交回复
热议问题