Role in Java constructor (rpm)

https://blog.csdn.net/vipmao/article/details/51530954, I think in a very good, learned a

The maximum effect is to complete the constructor to initialize the object is created, when we are in a new object and pass parameters will automatically call the constructor and the completion of initialization parameters. as follows:


the Test class {public
Private String name;
// constructor arguments have
public the Test (String name) {
this.name = name;
}

public static void main (String [] args) {
// new new object, parameter passing, call constructor
the Test Test the Test new new = ( "VipMao");
System.out.println (test.name);
}
}

Operating results VipMao
  This shows that when we created Test object will automatically call the constructor to initialize, then the name attribute of the program became VipMao.

  When it comes to the top in order to complete the constructor to initialize the properties of the incoming parameters in new objects, some people may not understand, why do not I write a constructor to initialize the program still can be done.

1. If you do not write a constructor, the program will automatically add you to a no-argument constructor no operation (of course you can not see).
2. If you write a constructor, the constructor will cover custom no-argument constructor.
3. If the no-argument constructor does not exist you write constructor will not be able to new XXX ( ""); parameter passing this way generates an object class (after, of course you can also generate objects through their set, get method assignment).
for example the above procedure the following change:
Import of java.util.ArrayList;
Import the java.util.Iterator;
Import java.util.List;

public class the Test {
Private String name;
// not a constructor
static void main public (String [] args) {
// new new object, parameter passing, the constructor is called
the Test Test the Test new new = ( "VipMao");
System.out.println (test.name);
}
}

When an object is created and assigned, the program will error:
at The constructor the Test (String) IS undefined, the constructor is not defined.
This means that if the programmer did not provide any constructors for the JAVA class, the system will provide a no-argument for this class constructor, the implementation of this constructor body is empty, do not do anything. In any case, JAVA class contains at least one constructor, if you provide multiple constructors (different parameters), the program will be based on your incoming calls Different parameters of the constructor.
----------------
Disclaimer: This article is the original article CSDN bloggers "VipMao", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. .
Original link: https: //blog.csdn.net/vipmao/article/details/51530954

Guess you like

Origin www.cnblogs.com/cocobear9/p/12609663.html