简体   繁体   中英

Why class instance itself has no public constructor?

While reading Reflection API i got this "Every Java Type has a class Instance And the class instance itself has no public Constructor" .

Now this is really confusing for me. Because what i have read till now says . All classes have constructor even when we don't specify any, we get constructor by default (even if the class is static) once we create its instance. Can someone explain me this in simple word

(to show even static class has constructor)

public class Reader1 {
    private int pageNumber;

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

    }
} 

using javap

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

It says: no public constructor . That doesn't mean it has no constructor at all. It does have a private constructor, which you can also create, as below given class, which also doesn't have a public constructor.

class Test {
    private Test() { }
}

“每个 Java Type 都有一个类 Instance 而类实例本身没有公共构造函数”这意味着 java.lang.Class 没有公共构造函数,因为只有 JVM 可以创建 java.lang.Class 实例,并且每个类 Java Type 都有一个 java.lang.Class 实例。我认为这就是你感到困惑的原因。

In Java you can suppress a public constructor by defining it private in the inheriting class - for Class this means:

public final class Class<T> {
  private Class() {
    //this constructor is private, no other constructor exists or will be generated
  }
}

To create an instance of class there exist some factory methods, like Class.forName .

Directly cited from the official website. I hope it can help you.

The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. Class has no public constructor . Instead a Class object is constructed automatically by the Java Virtual Machine when a class loader invokes one of the defineClass methods and passes the bytes of a class file.

https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM