make class only instantiable from specific class

血红的双手。 提交于 2021-02-07 20:30:04

问题


Let's say I have 3 classes class1, class2 and class3.

How can I have it that class1 can only get instantiated by class2 (class1 object = new class1()) but not by class3 or any other class?

I think it should work with modifiers but I am not sure.


回答1:


I want to rename your classes to Friend, Shy and Stranger. The Friend should be able to create Shy, but Stranger should not be able to.

This code will compile:

package com.sandbox;

public class Friend {

    public void createShy() {
        Shy shy = new Shy();
    }

    private static class Shy {

    }

}

But this code won't:

package com.sandbox;

public class Stranger {

    public void createShy() {
        Friend.Shy shy = new Friend.Shy();
    }

}

In addition, if we create a new class called FriendsChild, this won't compile either:

package com.sandbox;

public class FriendsChild extends Friend {

    public void childCreateShy() {
        Shy shy = new Shy();
    }

}

And this naming convention makes sense when you think about it. Just because I'm a friend of someone doesn't mean my child knows them.

Notice that all these classes are in the same package. As far as I can understand, this is the scenario you're looking for.




回答2:


Another option besides making the constructor protected:

  • Make the class1 constructer private
  • Make a public static factory method that requires a valid instance of class2 inorder to return an instance of class1



回答3:


Make class1 inner class of class2.




回答4:


Update

make protected constructor and put the eligible class in same package, if you want any class outside of package to construct this instance then you need that class to extend ClassA in this example,

if you restrict it then go for default access specifier

package com.somthing.a;
public class ClassA {

    ClassA() {
        super();
        // TODO Auto-generated constructor stub
    }
}

package com.something.a;
public class ClassB {
    public static void main(String[] args) {
        new ClassA();//valid
    }
}


package com.something.c;
public class ClassC {
    public static void main(String[] args) {
        new ClassA();// invalid
    }
}


来源:https://stackoverflow.com/questions/14366312/make-class-only-instantiable-from-specific-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!