What is the constructor method in java |
您所在的位置:网站首页 › java中的构造方法是什么 › What is the constructor method in java |
The function of the constructor method is to initialize the class. If you do not agree on the form of any constructor, the program will take a constructor without any parameters for you. Then you can only use the method without parameters when generating a class object, such as: class a {}// There isn't any constructor. The name of the constructor must be the same as the class name, including upper and lower case; The constructor has no return value and cannot be modified with void. If you are not careful Adding a return value type in front of the constructor will turn the constructor into an ordinary method, and an error that the constructor cannot be found will be generated at runtime. A class can define multiple constructors. If no constructor is defined when defining a class, the compilation system will automatically insert a parameterless default constructor, which does not execute any code. Constructor methods can be overloaded according to the number, type, and order of parameters. Examples are as follows: class Person //人类{ public Person(String n,int a) //构造方法 { name = n; age = a; } private string name; private int age; } static void main(String[] args){ Person p = new Person("张三",14);//这就是作用,为其初始化 }Copy after loginConstructor is used when new an object, For example: Hello hello = new Hello();//这时调用的是Hello的无参数构造方法; Hello hello = new Hello("hi");//这个是调用Hello有参数构造方法,Copy after loginIn JAVA, if you do not write a constructor, a parameterless constructor will be added by default. However, if there is already a parameterized constructor, the parameterless constructor will not be added by default. . If the Hello class already has a constructor with parameters, then an error will occur when using Hello hello = new Hello(); to create an object. This is why the book emphasizes writing If you have a parameterized constructor, it is best to add a parameterless constructor. The above is the detailed content of What is the constructor method in java. For more information, please follow other related articles on the PHP Chinese website! |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |