Learning the Javase object-oriented part, we should also make a summary of the construction method.
A construction method
In most cases, the final step of initializing an object is to invoke the constructor of the object. The construction method is responsible for initializing the object,
The instance variable is given the appropriate initial value. The constructor method must satisfy the following syntax rules:
(1) The method name must be the same as the class name;
(2) Do not declare the return type;
(3) cannot be modified by static, final, synchronized, abstract and native. The construction method cannot inherit from the quilt class, so use final and abstract
There is no point in retouching. The constructor method is used to initialize a newly created object, so there is no point in using static modifiers. Multiple threads do not create memory address phases at the same time
The same object, so it is not necessary to modify it with synchronized. In addition, the Java language does not support the construction of native types.
Example: In the following sample class, the sample (int x) method with an int return type is just a normal instance method and cannot be constructed as a method:
<span style= "FONT-SIZE:18PX;" >public class Sample { private int x; Construction method without parameters public Sample () {this (1); } Construction method with parameters public Sample (int x) { this.x=x; } is not a constructor method, is a generic instance method of public int Sample (int x) { return x + +; }} </span>
Although the above example can be compiled through, but the instance method and construction method with the same name, not good programming habits, easy to cause confusion.
Example: The Mystery () method of the following mystery class has a void return type and is therefore a normal instance method:
<span style= "FONT-SIZE:18PX;" >public class Mystery {Private String s;//is not a constructor method public void Mystery () {s = "constructor";} void Go () {System.out.println (s); } public static void Main (string[] args) {Mystery m = new Mystery (); M.go (); }} </span>
The printed result of the above program is null. Because the mystery instance is created with the new statement, the default constructor method of the mystery class is called instead of
The Mystery () method on which there is a void return type.
Two overloaded construction method
When an object is created by using the new statement, the object may have different initialization behavior under different conditions. You can use the overloaded construction method to table
Multiple initialization behavior of the object. The following methods of constructing the employee class are available in three overloaded forms. In multiple construction methods for a class, you may receive
Some repetitive operations. To improve the reusability of code, the Java language allows the use of this statement to invoke another constructor method in a constructor.
For example, for a new employee in the company, at the outset, it is possible that his name and age are unknown, and it is possible that only his name is
Known, it is also possible that the name and age are known. If the name is unknown, set the name to "anonymous", and if the age is unknown,
Set the age to-1.
Example: Employee.java source file code:
<span style= "FONT-SIZE:18PX;" >public class Employee { private String name; private int age; This constructor method is called when the employee's name and age are known : Public employee (String name, int ages) {this.name = name; this.age=age; } This constructor is called when the employee's name is known and the age is unknown, public Employee (String name) {This (name,-1); } When the employee's name and age are unknown, call this construction method public Employee () {This ("anonymous"); } public void SetName (String name) {this.name=name; } Public String GetName () {return name; } public void Setage (int.) {this.age=age; } public int getage () {return age; } public static void Main (string[] args) {Employee Zhangsan=new employee ("Zhang San"); Employee Lisi=new Employee ("John Doe"); Employee Someone=new employee (); }} </span>
The Mian () method in the above program creates three employee objects, respectively, by three construction methods. In the employee (String name) constructor method
The This (NAME,-1) statement is used to call the employee (String Name,int Age) Construction method. In the employee () construction method, this ("anonymous")
Statement is used to call the employee (String name) construction method.
When you use the this statement to invoke other construction methods, you must adhere to the following syntax rules:
(1) If the This statement is used in a constructor method, it must be the first statement of the construction method (regardless of the comment statement). The following construction party
Law is illegal:
<span style= "FONT-SIZE:18PX;" >public Employee () { String name= "anonymous"; This (name);//Compile error, this statement must be the first statement}</span>
(2) The This statement can be used only in a constructor method to invoke the other constructor methods of the class, and cannot be used in an instance method to invoke the class's other constructs
Manufacturing methods.
(3) Other construction methods can be invoked only with the this statement, and not directly by method names. The following method is called for the constructor method
Illegal:
<span style= "FONT-SIZE:18PX;" >public Employee () { String name= "anonymous"; Employee (name); Compile error, constructor method cannot be called directly by method name}</span>
Three default construction methods
The default constructor method is a constructor without parameters and can be divided into two types:
A implied default construction method;
The B program explicitly defines the default constructor method.
In the Java language, each class has at least one construction method. To ensure this, if no construction method is provided in the user-defined class, the
? The Java language will automatically provide an implicit default constructor method. The constructed method has no parameters, is decorated with public, and the method body is empty, in the form of:
<span style= "FONT-SIZE:18PX;" >//implied default construction method public ClassName () {} </span>
You can also explicitly define a default construction method in your program, which can be any level of access. For example:
<span style= "FONT-SIZE:18PX;" The default constructor method explicitly defined by the >//program protected Employee () {This ("anonymous");} </span>
If one or more construction methods are explicitly defined in a class, and all of the constructor methods have parameters, the class loses its default construction method.
In the following program, the Sample1 class has an implicit default construction method, the Sample2 class has no default constructor, and the Sample3 class has an explicit definition
The default constructor method:
<span style= "FONT-SIZE:18PX;" >class sample1{}class sample2{public Sample2 (int a) { System.out.println ("My Constructor");} } Class sample3{public Sample3 () { System.out.println ("My Default Constructor");} } </span>
You can call the default construction method of the Sample1 class to create a Sample1 object: Sample1 s=new Sample1 (); Legal
The Sample2 class does not have a default construction method, so the following statement causes a compilation error: Sample2 s=new Sample2 (); Compilation error
The Sample3 class explicitly defines the default constructor method, so the following statement is legal. Sample3 s=new Sample3 ();
The construction method of calling the parent class with the four sub-class
The construction method of the parent class cannot inherit from the quilt class. The following myexception classes inherit the Java.lang.Exception class:
<span style= "FONT-SIZE:18PX;" >//MyException class has only one implicit default construction method public class MyException extends exception{} </span>
Although the following form of construction is defined in the exception class:
<span style= "FONT-SIZE:18PX;" >public Exception (String msg) {}</span>
However, the MyException class does not inherit the constructor of the above exception class, so the following code is not valid:
<span style= "FONT-SIZE:18PX;" >exception e=new myexception ("Something is Error");//Compile error, MyException class does not exist such construction method </span>
In the constructor of a subclass, the constructor of the parent class can be called through the Super statement. For example:
<span style= "FONT-SIZE:18PX;" >public class MyException extends exception{public myexception () { //Call Exception parent Exception (String msg) Construction method Super ("Something is Error"); } Public myexception (String msg) { //calls Exception parent class exception (string msg) construction method Super (msg);} } </span>
When you invoke the constructor method of a parent class with a super statement, you must adhere to the following syntax rules.
(1) In the constructor method of a subclass, you cannot call the constructor of the parent class directly from the parent class method name, but instead use the Super statement.
The following code is illegal:
<span style= "FONT-SIZE:18PX;" >public myexception (String msg) { Exception (msg);//Compile Error}</span>
(2) When using the Super statement, it must be placed at the front.
The following code is illegal:
<span style= "FONT-SIZE:18PX;" >public myexception () { String msg= "Something wrong"; Super (MSG); Compilation error, the Super statement must be the first statement of the construction method}</span>
When you create an object of a subclass, the Java Virtual machine first executes the constructor of the parent class, and then executes the constructor of the subclass. In the case of multilevel inheritance
, the constructor of each class is executed from the topmost parent of the inheritance tree, which guarantees that the subclass object is relayed from all direct or indirect parent classes
The instance variables of the commit are initialized correctly. For example, the following base parent and sub subclasses have one instance variable A and B, and when you construct a sub instance, the two
Each instance variable will be initialized.
Instance code:
<span style= "FONT-SIZE:18PX;" >class Base{private int A; Public Base (int a) {this.a=a;} public int Geta () {return A;}} public class Sub extends base{private int b; Public Sub (int a,int b) {super (a); this.b=b;} public int Getb () {return b;} public static void Main (String args[]) {sub sub=new sub); System.out.println ("a=" +sub.geta () + ", b=" +sub.getb ()); Print A=1 b=2 }}</span>
Operation Result:
a=1,b=2
In the following example, the son class inherits the Father class, and the Father class inherits the Grandpa class. These three classes explicitly define the default construction method, which
A construction method with parameters is also defined.
Son.java Source file Code:
<span style= "FONT-SIZE:18PX;" >class grandpa{ protected Grandpa () { System.out.println ("Default Grandpa"); } Public Grandpa (String name) { System.out.println (name);} } Class Father extends grandpa{ protected Father () {System.out.println ("default Father"); } Public Father (String grandpaname,string fathername) {super (grandpaname); System.out.println (Fathername); }} public class son extends father{public Son () {System.out.println ("default Son"); Public Son (String grandpaname,string fathername,string sonname) {super (grandpaname,fathername); System.out.println (Sonname); } public static void Main (String args[]) {son s1= new son ("My Grandpa", "My Father", "my Son"); Son s2=new son ();} } </span>
The results of the program run as follows:
When the subclass's construction method does not explicitly invoke the constructor of the parent class with the Super statement, the Java virtual object is created by using this constructor method.
The proposed opportunity automatically first calls the parent class's default constructor.
When the constructor of a subclass does not explicitly invoke the constructor of the parent class with the Super statement, and the parent class does not provide a default constructor method, the
Translation errors. We comment out the protected level of the Grandpa class, so that the Grandpa class loses its default construction method,
The default constructor method for the Father class is not compiled because the default constructor method of the Grandpa class is not found. If you put the default constructor of the Grandpa class
The protected access level of the method to private access level will also cause compilation errors because the default constructor method of the Father class cannot access the Grandpa class
The private default constructor method.
In the following example, the default constructor method of a subclass sub does not invoke the constructor of the parent class through the Super statement, but instead calls itself through the this statement
Another constructor for the sub (int i), and the base (int i) constructor of the parent class base is called by the Super statement in sub (int i). This way, whether through
The base (int i) construction method of the parent class base is called when the sub class is constructed to create a sub instance.
Sub.java Source file Code:
<span style= "FONT-SIZE:18PX;" >class base{base (int i) {System.out.println ("Call Base (int i)");}} public class Sub extends Base{sub () {this (0); System.out.println ("Call Sub ()");} Sub (int i) {super (i); System.out.println ("Call Sub (int i)");} public static void Main (String args[]) { Sub sub=new sub ();} } </span>
The results of the program execution are as follows:
Five scope of the construction method
The constructor method can only be called in the following ways:
(1) Other constructor methods of the current class call it through the this statement.
(2) The construction method of the subclass of the current class is called by the Super statement.
(3) Call it through the new statement in the program.
Notice how the following constructor is called:
Sub.java Source file Code:
<span style= "FONT-SIZE:18PX;" >class base{Public Base (Int. I,int j) { } public Base (int. i) {this (i,0);//Legal Base (i,0);//Compile Error } }class Sub extends base{public Sub (int i,int j) {super (i,0);//Legal } void method1 (int i,int j) {this (i,j);//Compile Error Sub (I,J); Compilation error } void Method2 (int i,int j) {super (I,J);//Compile error } void method3 (int i,int j) {Base s=new base (0,0 ); Legal S. Base (0,0); Compilation Error }}</span>
access level of the six-structured method
The construction method can be in one of the four access levels of public, protected, default, and private. This section focuses on the construction method at the private level
Other meanings. When the constructor method is private, it means that it can only be accessed in the current class: In other constructor methods of the current class, the this statement
Call it, and you can also call it through the new statement in the member method of the current class.
In one of the following situations, you can declare all the constructor methods of a class as private types:
(1) This class contains only static methods that are called by other programs, and there are no instance methods. Other programs do not need to create instances of this class,
You can access the static methods of the class. For example, the Java.lang.Math class fits this case, and in the Math class, a series of public static
method, in order to prohibit an external program from creating an instance of the math class, the only construction method of the math class is private: Private math () {}
If a class is an abstract class, it means that it is dedicated to inheriting classes, can have subclasses, and can create instances of specific subclasses. While the JDK
You do not want the user to create subclasses of the math class, in which case it is more appropriate to define the class's construction method as private type.
(2) Prohibit this class from being inherited. When all the constructor methods of a class are private types, if its subclasses are defined, then the subclass is constructed without
Method calls any of the constructor methods of the parent class, resulting in a compilation error. Declaring a class as the final type can also prohibit the class from being inherited. The area of the two
Don't be:
A If a class allows other programs to construct an instance of it with a new statement, but does not allow a subclass, declare the class as the final type.
b If a class does not allow other programs to construct its instance with the new statement, and it does not allow the owning of subclasses, then declare all of the constructor methods of the class as
Private type. Because most classes allow other programs to construct instances of it with new statements, it is more common to use the final modifier to prohibit classes from being inherited
See.
C This class needs to encapsulate the details of constructing its own instance, and does not allow other programs to create instances of this class from the new statement, this class to other
The program provides a static method that obtains its own instance, which is called a static factory method.
Javase Getting Started learning 23:java Object-oriented construction method