Constructor Inside Inner Static Class in java?

2019-06-23 16:51发布

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)

标签: java oop javap
1条回答
聊天终结者
2楼-- · 2019-06-23 17:19

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.

查看更多
登录 后发表回答