title: Java: make package level constructor in a class accessible for outer packages. Allow only certain classes inside project access to constructor
body: <p>I'm developing a library and trying to keep everything organized. Thus, I have nested package structure and a single class that is supposed to have access to constructors to all other classes:</p>
  
  <p><strong><em>This is my project structure:</em></strong></p>
  
  <pre><code>src
     main
        java
           main
              Main.java
           zoo
              Zoo.java
              animals
                 Animal.java
                 mammals
                    Dog.java
                 fish
                    Salmon.java
                 birds
                    Falcon.java
  </code></pre>
  
  <p><strong><em>This is the code I have in a main method:</em></strong></p>
  
  <p><strong>Main.java</strong>:</p>
  
  <pre><code>Zoo zoo = new Zoo(password);
  Animal dog = zoo.getDog(name);
  Animal salmon = zoo.getSalmon(name);
  Animal falcon = zoo.getFalcon(name);
  </code></pre>
  
  <p><strong><em>I want to prevent a user from being able to create an animal directly (from outside of the <code>zoo</code> package):</em></strong></p>
  
  <pre><code>Animal dog = new Dog("Charlie");  //error - constructor isn't public
  </code></pre>
  
  <p>However I'm not sure how to accomplish it. I could put all classes inside the <code>zoo</code> package and make animal constructors only package-level accessible. <strong>However, I would have to sacrifice the package structur</strong>e and I'd rather not do that. </p>
  
  <p><strong>Zoo.java</strong>:</p>
  
  <pre><code>public class Zoo {
      private String password;
  
      public Zoo(String password)  {this.password = password;}
  
      public Dog getDog(String name)  {return new Dog(name);}
  
      public Salmon getSalmon(String name)  {return new Salmon(name);}
  
      public Falcon getFalcon(String name)  {return new Falcon(name);}
  }
  </code></pre>
  
  <p><strong>Animal.java</strong>:</p>
  
  <pre><code>public abstract class Animal {
      protected String name;
      public Animal(String name)  {this.name = name;}
  }
  </code></pre>
  
  <p><strong>animals</strong>:</p>
  
  <pre><code>public class Dog extends Animal {
      public Dog(String name) {super(name);}
  }
  public class Salmon extends Animal {
       public Salmon(String name) {super(name);}
  }
  public class Falcon extends Animal {
      public Falcon(String name)  {super(name);}
  }
  </code></pre>
  
  <p>So what can be done to accomplish the above? Pehaps there exists some pattern for it?</p>