Anonymous initialization of class with protected constructor

安稳与你 提交于 2020-05-25 18:48:19

问题


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?


回答1:


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.




回答2:


The first line fails, because SomeClass's constructor is protected and MainClass is not in SomeClass's package, and it isn't subclassing MainClass.

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




回答3:


Those two little braces in

SomeClass sac2 = new SomeClass() {};

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

  1. An anonymous subclass of SomeClass is created.
  2. That anonymous subclass is given a default no-argument constructor, just like any other Java class that is declared without a no-argument constructor.
  3. The default no-argument constructor is defined with visibility public
  4. The default no-argument constructor is defined to call super() (which is what no-arg constructors always do first).
  5. The new command calls the no-argument constructor of this anonymous subclass and assigns the result to sac2.

The default no-argument constructor in the anonymous subclass of SomeClass has access to the protected constructor of SomeClass because the anonymous subclass is a descendant of SomeClass, so the call to super() is valid. The new statement calls this default no-argument constructor, which has public visibility.




回答4:


Your line

SomeClass sac2 = new SomeClass() {};

creates an instance of a new class which extends SomeClass. Since SomeClass defines a protected constructor without arguments, a child class may call this implicitly in its own constructor which is happening in this line.



来源:https://stackoverflow.com/questions/28073047/anonymous-initialization-of-class-with-protected-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!