3

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.

maddo7
  • 4,503
  • 6
  • 31
  • 51

4 Answers4

2

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.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
1

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
Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
0

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
    }
}
jmj
  • 237,923
  • 42
  • 401
  • 438
0

Make class1 inner class of class2.

DcodeChef
  • 1,550
  • 13
  • 17