Constructor Inside Inner Static Class in java?

点点圈 提交于 2020-01-03 09:44:37

问题


I Wrote the following Code

public class Reader1 {
    private int pageNumber;

    private class ReaderName1{
        public int getPage(){
        return pageNumber;
        }
    }
    static class ReaderFound{

    }
}

When I used the Java Class File Disassembler javap on the compiled code I got

1. for Reader1.class



class Reader1$ReaderName1 {
              final Reader1 this$0;
              private Reader1$ReaderName1(Reader1);
              public int getPage();
            }


2. for Reader1$ReaderName1.class



    public class Reader1 {
          private int pageNumber;
          public Reader1();
          static int access$000(Reader1);
        }

3. for Reader1$ReaderFound.class



     class Reader1$ReaderFound {
          Reader1$ReaderFound();
        }

My question is since ReaderFound is a static class how can it have an default constructor ? If so why ? Is it allowed ?

If allowed what kind of constructor is this that is found inside the class Reader1$ReaderFound because it can't be static. (Also since constructor are implicitly called to initilize an object and since ReaderFound is an static class so there would we no object of it. My point for first question)


回答1:


There are four kinds of nested classes in Java: static member classes, nonstatic member classes, anonymous classes, and local classes.

A static member class can be seen as an ordinary class that is declared inside another class. It does not need an instance of the enclosing class to be instantiated. Since no instance is required, it has no access to instance methods and variables from the enclosing class. It is able to access class members though, even if they are private.

class EnclosingClass {
    static class StaticMemberClass { }

    public static void main(String... args) {
        EnclosingClass.StaticMemberClass nestedInstance =
            new EnclosingClass.StaticMemberClass();
    }
}

Being a static nested class does not mean you can't create an instance from it. Thus, a default constructor will be created if you do not create a custom one.



来源:https://stackoverflow.com/questions/29260297/constructor-inside-inner-static-class-in-java

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