Implement a final class without the “final” keyword

后端 未结 7 1621
生来不讨喜
生来不讨喜 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:03
    public class Immutable {       
        private int val;
    
        public Immutable(int v)
        { 
            this.val = v;
        }
    
        public int getVal() { return this.val; }
    }
    
    0 讨论(0)
  • 2020-12-29 11:10
    • Mark constructor as private
    • Provide a static method on the class to create instance of a class. This will allow you to instantiate objects of that class
    0 讨论(0)
  • 2020-12-29 11:12

    Make all the constructors of that class as private to stop inheriting, Though not recommended.

    0 讨论(0)
  • 2020-12-29 11:12

    Static classes can't be inherited from

    0 讨论(0)
  • 2020-12-29 11:14

    Create a private constructor without parameters?

    public class Base
    {
        private Base()
        {
        }
    }
    
    public class Derived : Base
    {
    //Cannot access private constructor here error
    }
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题