Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous initialization of class with protected constructor

Let's assume we have a class:

public class SomeClass {    
    protected SomeClass () { 
    }
}

In MainClass located in different package I tried to execute two lines:

public static void main(String[] args) {
    SomeClass sac1 = new SomeClass(); 
    SomeClass sac2 = new SomeClass() {}; 
}

Because of protected constructor, in both cases I was expecting program to fail. To my suprise, anonymous initialization worked fine. Could somebody explain me why second method of initialization is ok?

like image 684
Tinki Avatar asked Jan 21 '15 17:01

Tinki


1 Answers

Your anonymous class

SomeClass sac2 = new SomeClass() {}; 

basically becomes

public class Anonymous extends SomeClass {
    Anonymous () {
        super();
    }
}

The constructor has no access modifier, so you can invoke it without problem from within the same package. You can also invoke super() because the protected parent constructor is accessible from a subclass constructor.

like image 83
Sotirios Delimanolis Avatar answered Oct 24 '22 08:10

Sotirios Delimanolis