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

Pyrrha
  • 159
  • 2
  • 12
  • 1
    Can be called from the same package. Check here: http://stackoverflow.com/questions/215497/in-java-difference-between-default-public-protected-and-private – midor Nov 30 '16 at 08:54
  • But it's marked as abstract in the snippet above. – aioobe Nov 30 '16 at 09: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](http://stackoverflow.com/a/33627846/276052). – aioobe Nov 30 '16 at 09:06

1 Answers1

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

Cà phê đen
  • 1,883
  • 2
  • 21
  • 20