简体   繁体   中英

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

将该类的所有构造函数设置为private以停止继承,尽管不推荐。

public class Immutable {       
    private int val;

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

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

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
}

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

静态类不能继承

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM