开发者

Implement a final class without the "final" keyword

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 over. just out of curiosity now ) 10x.


  • 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


I don't know what they mean exactly mean by a final class. If they mean a class that cannot be extended by inheritence, than clearly this cannot be done, except by marking that class with final (or sealed, or whatever the language keyword is).

But if the mean final as in immutable, such that a derived class can't modify the value of the fields in the class,than the base class should have all of the fileds and accessor methods private.


Create a private constructor without parameters?

public class Base
{
    private Base()
    {
    }
}

public class Derived : Base
{
//Cannot access private constructor here error
}


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


public class Immutable {       
    private int val;

    public Immutable(int v)
    { 
        this.val = v;
    }

    public int getVal() { return this.val; }
}


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);
    }
}


Static classes can't be inherited from

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜