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();
}
Create a factory method and protect the constructor:
public class Dog implements Animal {
protected Dog () {
}
public static Animal createAsAnimal () {
new Dog ();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With