Anonymous class initialization with protected constructor

Suppose we have a class:

public class SomeClass { protected SomeClass () { } } 

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

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

Due to the protected constructor in both cases, I expected the program to end with an error. To my surprise, anonymous initialization worked fine. Can someone explain to me why the second initialization method is ok?

+5
source share
4 answers

Your anonymous class

 SomeClass sac2 = new SomeClass() {}; 

basically becomes

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

The constructor does not have an access modifier, so you can call it without problems from the same package. You can also call super() , since the parent constructor protected is accessible from the constructor of the subclass.

+8
source

The first line fails because the SomeClass protected constructor and MainClass not in the SomeClass package, and it is not a subclass of MainClass .

The second line succeeds because it creates an anonymous subclass of SomeClass . This anonymous inner class is a subclass of SomeClass , so it has access to the SomeClass protected constructor. The default constructor for this anonymous inner class implicitly calls this superclass constructor.

+3
source

These two little braces in

 SomeClass sac2 = new SomeClass() {}; 

cause a lot of automatic behavior in Java. Here's what happens when this line is executed:

  • An anonymous subclass of SomeClass .
  • This anonymous subclass defines a constructor with no arguments by default, like any other Java class declared without a constructor without arguments.
  • The default constructor without arguments is determined by the visibility public
  • A default constructor without arguments is defined as a call to super() (this is what no-arg constructors always do).
  • The new command calls the constructor without arguments of this anonymous subclass and assigns the result to sac2 .

A constructor with no default arguments in an anonymous subclass of SomeClass has access to the protected SomeClass , because an anonymous subclass is a descendant of SomeClass , so the call to super() is SomeClass new operator invokes this constructor without default arguments, which has public visibility.

+2
source

Your line

 SomeClass sac2 = new SomeClass() {}; 

instantiates a new class that extends SomeClass . Because SomeClass defines a protected constructor with no arguments, the child class can invoke this implicitly in its own constructor, which happens on this line.

0
source

Source: https://habr.com/ru/post/1211641/


All Articles