Default Constructor Visibility in Java [duplicate]

丶灬走出姿态 提交于 2020-01-06 11:45:46

问题


I'm confused about the actual visibility of default constructors. I have been given the following code in a book that explains there is a default constructor created, but does not physically show one (i.e. Employee()), despite it being automatically assigned:

public class Employee {
private String name;
private int zip;
private int age;
}

In another book I am told this the following is a default constructor as it takes no arguments:

public class Pet {
private String name;
private int weight;

Pet(){}
}

Is this latter constructor actually default if I'm physically defining it? Or is the default constructor invisible to my code as in the first example because of something relating to the superclass?

Edit: I'm asking about the physical code that is written into a class. One source is telling me that the default constructor is explicitly written out, the other telling me that it will not appear in the code and is essentially assumed to exist though it is not apparent to the user. My issue comes that the explicit one is coming from a java cert study guide so it's causing some confusion for me.


回答1:


The default constructor is a public no arguments constructor. To be more specific it has the same access level as the class, so public in a public class, private in a private class, etc.

In your second example you are creating a package access level constructor.

This means that anyone outside of the same package will be able to see and use instances of the class (since it is a public class) but not create new ones.

Because you have defined a constructor the default constructor will not be created.

Just having no arguments does not make something a default constructor. A default constructor is added automatically by the compiler, you have no code at all for it.




回答2:


If you don't write any constructors in your Class, then Java Compiler adds default no argument constructor. If you write any constructors in your class, then Java Compiler DOES NOT add default no argument constructor to the Class.

Please refer the same from the below Oracle site: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html



来源:https://stackoverflow.com/questions/33633413/default-constructor-visibility-in-java

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