Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick Java Question: Instantiating a given class only from another?

My problem is thus: I need a way to ensure only one given class can instantiate another. I don't want to have to make the other a nested inner class or something dumb like that. How do I do this? I forget offhand.

like image 645
Daddy Warbox Avatar asked Mar 02 '23 02:03

Daddy Warbox


1 Answers

A private static inner class is exactly what you want. Nothing dumb about it.

public class Creator {
  private static class Created {
  }
}

Otherwise you can only protect instantiation on the package level.

public class Created {
  Created() {
  }
}

Which gives only classes from the same package access to the constructor.

like image 183
tcurdt Avatar answered Apr 06 '23 20:04

tcurdt