mardi 30 avril 2019

How to prevent instances of subclasses without using the parent class Builder

I have a Class called State inside my library. I have a builder for it inside the class, accessed through State.Builder.build(). I need it to be instantiated only by that builder.

I want others using my library to extend and create their states, like CustomState, but not be able to instantiate those subclasses of State without using State.Builder.

Java doesn't seem to support it in the ways I've tried. if I use a private constructor in State class, the child classes show a compilation error "There is no default constructor available in com.example.State"

if I use a protected constructor, no error, but the subclasses can be instantiated with a simple new CustomState() statement.

if I use no modifier (package level access), still the subclass can be instantiated even if the class it's instantiated from has another package name.

any ideas?

Thanks





Aucun commentaire:

Enregistrer un commentaire