Search code examples
javaconstructorprotected

Able to create a var with protected constructor?


I'm on a project where I have a Actor class, with methods and data members into it. It's like an abstract class, but I don't find useful to set it abstract (every methods are implemented).

public abstract class Acteur {
    /**
     * Empêchement d'instancier un acteur
     */
    protected Acteur() { }
}

The thing is that in a test, I can instantiate an actor :

import org.junit.Test;

public class ActeurTest {

    @Test
    public void testActeurConstructeur() {
        Acteur acteur = new Acteur();
    }
}

So my question is : how can that be possible ? I was wondering that only sub-classes can use/override a protected constructor ?

Thanks


Solution

  • For the question you are wondering that only sub-classes can use/override a protected constructor.

    protected can be accessed within same package.

    Access Modifiers  In class     Same package    Anywhere but subclasses    Outside package & non relate
    Private               Y             N                   N                          N
    Default               Y             Y                   N                          N
    Protected             Y             Y                   Y                          N
    Public                Y             Y                   Y                          Y
    

    Java Access Modifiers