Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect class to be instantiated directly

Tags:

java

uml

How can I change this implementation:

public interface Animal()
{
   public void eat();
}

public class Dog implements Animal
{
   public void eat()
   {}
}

public void main()
{
   // Animal can be instantiated like this:
  Animal dog = new Dog();

  // But I dont want the user to create an instance like this, how can I prevent this declaration?
  Dog anotherDog = new Dog();
}
like image 915
olidev Avatar asked Dec 21 '25 09:12

olidev


1 Answers

Create a factory method and protect the constructor:

public class Dog implements Animal {
   protected Dog () {
   }

   public static Animal createAsAnimal () {
      new Dog ();
   }
}
like image 72
Alexander Pogrebnyak Avatar answered Dec 23 '25 00:12

Alexander Pogrebnyak