Constructor in Java

Source: Internet
Author: User

Summary of constructor methods in Java today's code writing suddenly found that Java constructor also has a lot of arguments, nothing to worry about. Summary: The difference between constructor methods and instance methods: i. The main difference lies in three aspects: modifier, return value, name 1. Like the instance method, the constructor can have any access modifier, public, private, protected, or without modifiers, you can modify the constructor. Unlike the instance method, the constructor cannot have any non-access modifier, such as static, final, synchronized, and abstract. Explanation: constructor is used to initialize an instance object, so static modification has no significance. Multiple Threads do not create the same object with the same memory address at the same time, So synchronized modification has no significance; constructor methods cannot inherit from quilt classes, so final and abstract modification are meaningless. 2. The return type is very important. The instance method can return any type value or no return value (void). The constructor does not return the type, and the void does not. 3. As for naming, the constructor is the same as the class name. Of course, the instance method can also be the same as the class name, but it is customary that we usually name the instance method in lower case, on the other hand, it is also separated from the constructor. The constructor is the same as the class name, so the first letter is generally capitalized. Let's take a few examples to get familiar with: public class Sample {private int x; public Sample () {// The construction method without parameters this (1) ;}public Sample (int x) {// constructor with parameters this. x = x ;}public int Sample (int x) {// not the constructor return x ++ ;}} in the above example, we can easily partition without commenting. Let's look at the following example: public class Mystery {private String s; public void Mystery () {// not the constructor Construction Method s = "constructor";} void go () {System. out. println (s);} public static void main (String [] args) {Mystery M = new Mystery (); m. go () ;}} the execution result of the program is null. Although Mystery m = new Mystery (); calls the construction method of the Mystery class, but public void Mystery () it is not a constructor. It is just a common instance method. Where is the constructor of this class? 2. Let's talk about the Default Construction Method of java. We know that each class must have at least one constructor in java. To ensure this, when the user does not define a clear constructor for the java class, java provides us with a default constructor. This constructor has no parameters, the modifier is public and the method body is empty. In fact, the default constructor can be divided into two types: hidden constructor, and display default constructor. if one or more constructor methods are defined in a class and each constructor has a parameter form, there is no default constructor for this class. See the following example. Public class Sample1 {} public class Sample2 {public Sample2 (int a) {System. out. println ("My Constructor") ;}} public class Sample3 {public Sample3 () {System. out. println ("My Default Constructor") ;}} Sample1 in the above three classes has an implicit Default Constructor. The following statement Sample1 s1 = new Sample () is valid; sample2 does not have a default constructor. The following statement Sample2 s2 = new Sample2 () is invalid. If Sample2 () is executed, a compilation error occurs. Sample3 has a displayed default constructor, therefore, the following statement Sample3 s3 = new Sample3 (); is valid. Iii. Use of this and super in the instance method and constructor. "this" can be used in the instance method. It points to the Instance Object of the class that is executing the method. Of course, this object cannot be used in the static method, because the static method does not belong to the Instance Object of the class, the this keyword can also be used in the constructor. this In the constructor is another constructor pointing to different parameters of the same object. Let's take a look at the following code: public class Platypus {String name; Platypus (String input) {name = input;} Platypus () {this ("John/Mary Doe");} public static void main (String args []) {Platypus p1 = new Platypus ("digger "); platypus p2 = new Platypus (); System. out. println (p1.name + "----" + p2.name) ;}} the above Code contains two constructors. The first constructor assigns a value to the member name of the class, the second constructor calls the first constructor to give the class member name an initial value Jonn/Mary Doe so the program execution result is: digger ---- John/Mary Doe The following two points are: 1. When other constructor methods are called using the this keyword in the constructor, the Code must be placed in the first line; otherwise, compilation errors may occur. 2. Only one other constructor can be called by using this in constructor. Usage of "super": the super keyword in the instance method and constructor method is used to direct to the parent class, and the super keyword in the instance method is used to call a method in the parent class, see the following code: class getBirthInfo {void getBirthInfo () {System. out. println ("born alive. ") ;}} class Platypus1 extends getBirthInfo {void getBirthInfo () {System. out. println ("hatch from eggs"); System. out. println ("a mammal normally is"); super. getBirthInfo () ;}} public class test1 {public static void main (String [] args) {Platypus1 p 1 = new Platypus1 (); p1.getBirthInfo () ;}} the preceding example uses super. getBirthInfo (); To call the void getBirthInfo () method of its parent class. The super keyword is used in the constructor to call the constructor in the parent class. See the following code: class getBirthInfo {getBirthInfo () {System. out. println ("auto");} void aa () {System. out. println ("born alive. ") ;}} class Platypus1 extends getBirthInfo {Platypus1 () {super (); System. out. println ("hatch from eggs"); System. out. println ("a mammal normally is") ;}} public class test1 {public static void main (String [] args) {Platypus1 p1 = new Platypus1 ();}} I executed the code Super in the constructor calls the constructor of the parent class. The Inheritance Mechanism of the class allows the subclass to call the function of the parent class. The following describes the class initialization sequence in the inheritance relationship. Please refer to instance 1: class SuperClass {SuperClass () {System. out. println ("SuperClass constructor") ;}} public class SubClass extends SuperClass {SubClass () {System. out. println ("SubClass constructor");} public static void main (String [] args) {SubClass sub = new SubClass () ;}} execution result: in the code of SuperClass constructor SubClass constructor, we only instantiate a SubClass object. However, from the execution result, the program is not a constructor, but a constructor. Execute the default constructor of the parent class, and then execute the constructor of the Child class. therefore, when instantiating a subclass object, the program will first call the default constructor of the parent class, and then execute the constructor of the subclass. Let's look at instance 2: class SuperClass {SuperClass (String str) {System. out. println ("Super with a string. ") ;}} public class SubClass extends SuperClass {SubClass (String str) {System. out. println ("Sub with a string. ");} public static void main (String [] args) {SubClass sub = new SubClass (" sub ") ;}} this program cannot be compiled successfully under JDK, because the default constructor of the parent class is called when the subclass object is instantiated, but its parent class does not have the default constructor, it cannot be compiled successfully. Solution: 1. Add a displayed default constructor to the parent class. 2. Add a super (str) clause to the constructor and add the first statement to the constructor. Both methods can solve the program compilation problem, but the execution results are different. the first execution result is: Sub with a string. the second execution result is: Super with a string. sub with a string. the second method is not called even if the default constructor shown in the parent class. Let's look at Example 3: class One {One (String str) {System. out. println (str) ;}} class Two {One one_1 = new One ("one-1"); One one_2 = new One ("one-2 "); one one_3 = new One ("one-3"); Two (String str) {System. out. println (str) ;}} public class Test {public static void main (String [] args) {System. out. println ("Test main () start"); Two two = new Two ("two");} execution result: Test main () startone-1one-2one-3two we implemented But the program does not call the Two constructor before the Two object in the instance. Instead, it initializes the member variables of the Two class. The Two class has three member variables, they are all One class objects, so we need to execute the One class constructor in sequence, and then initialize the Two class objects. When an object of the class is instantiated, the member variables in the class will be initialized first. If the member variables in the class have objects, they will also perform initialization in order. After Initialization is complete, all Class Members call the constructor of the class where the object is located to create the object. Initialization is the role of the constructor. Let's look at Example 4: class One {One (String str) {System. out. println (str) ;}} class Two {One one_1 = new One ("one-1"); One one_2 = new One ("one-2 "); static One one_3 = new One ("one-3"); Two (String str) {System. out. println (str) ;}} public class Test {public static void main (String [] args) {System. out. println ("Test main () start"); Two two_1 = new Two ("two-1"); System. out. println ("------------"); Two two2 = New Two ("two-2") ;}} execution result: Test main () startone-3one-1one-2two-1 ------------ one-1one-2two-2 conclusion: If a class has a static object, then, it initializes non-static objects only once before initialization. Instead of static objects, they must be initialized each time they are called. Let's look at Example 5: class One {One (String str) {System. out. println (str) ;}} class Two {One one_1 = new One ("one-1"); One one_2 = new One ("one-2 "); static One one_3 = new One ("one-3"); Two (String str) {System. out. println (str) ;}} public class Test {static Two two3 = new Two ("two-3"); public static void main (String [] args) {System. out. println ("Test main () start"); Two two_1 = new Two ("two-1"); System. out. Println ("------------"); Two two2 = new Two ("two-2");} execution result: one-3one-1one-2two-3Test main () startone-1one-2two-1 ------------ one-1one-2two-2 conclusion: static variables of the main class in the program will be initialized before the main () method is executed. Only one-3 is output in the result. This also indicates that if a class has a static object, it will be initialized before the non-static object, but only once. Non-static objects must be initialized each time they are called. Summarized initialization sequence: 1. The static members of the main class are initialized first. 2. the constructor of the parent class of the primary class is called. 3. Non-static object (variable) initialization of the main class. 4. Call the constructor of the main class.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.