0

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

3
  • 1
    Can be called from the same package. Check here: stackoverflow.com/questions/215497/…
    – midor
    Nov 30, 2016 at 8:54
  • But it's marked as abstract in the snippet above.
    – aioobe
    Nov 30, 2016 at 9:03
  • When I try out your code, I get an error saying: "Acteur' is abstract; cannot be instantiated". Make sure you're editing the right files, done a clean compile and so on. You should not be able to construct an abstract class like that. If you're confused about the visibility of things declared as protected, have a look at this table.
    – aioobe
    Nov 30, 2016 at 9:06

1 Answer 1

1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.