Java constructor

Source: Internet
Author: User
Tags abstract inheritance instance method modifier valid


Understanding of constructor.

The constructor generally needs to meet the following rules:
(1) the method name must be consistent with the class name.
(2) do not declare the return type.
(3) it cannot be modified by static, final, synchronized, abstract, or native. Constructor methods cannot be inherited by the quilt class. Therefore, using final and abstract modifier makes no sense. The constructor is used to initialize a new object, so static modification is meaningless. Multiple threads do not create objects with the same memory address at the same time. Therefore, using synchronized modification is unnecessary. In addition, Java currently does not support native constructor methods.

Knowledge extension:

When using this statement to call other constructor methods, you must follow the following rules:
(1) if this statement is used in a constructor, it must be used as the first statement of the constructor (comment statements are not considered ).
(2) only the this statement can be used in one constructor to call other constructor methods of the class, rather than using this statement to call other constructor methods of the class in the instance method.
(3) you can only use this statement to call other constructor methods, rather than directly calling constructor methods through method names.
Similarly, when a super statement is used to call the constructor of the parent class, the following syntax rules must also be observed:
(1) in the constructor of the subclass, the constructor of the parent class cannot be called directly by the parent class method name. Instead, the super statement is used.
(2) If the subclass constructor has a super statement, it must be the first statement of the constructor.

Let's take a few examples to familiarize ourselves:
Public class Sample {
    
Private int x;
 
Public Sample () {// Constructor without parameters
This (1 );
    }
    
Public Sample (int x) {// Constructor with parameters
This. x = x;
    }
    
Public int Sample (int x) {// Not the constructor
Return x ++;
    }
 
}
Even if we do not comment on the above example, we can easily differentiate it. Let's look at the following example.
Public class Mystery {
Private String s;
    
Public void Mystery () {// Not the constructor
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 (); the constructor of the Mystery class is called, public void Mystery () is not the constructor, he is just a common instance method. Where does the constructor of this class go?

2. Let's talk about the default java constructor.
We know that the java language requires at least one constructor for each class. To ensure this, when the user does not define a clear constructor for the java class, java provides 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 and the execution will cause a compilation error.
Sample3 has a display default constructor, so the following statement Sample3 s3 = new Sample3 (); is valid.

III. Use of this and super in the instance method and constructor.
Usage of "this"
You can use the this keyword in the instance method. It points to the instance object of the class in which the method is being executed. 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 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 );
    }
}
In the code above, the class has 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 of Jonn/Mary Doe.
So the program execution result is: digger ---- John/Mary Doe
Note the following two points:
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. The super keyword in the instance method is 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 p1 = 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 ();
    }
}
After the code is executed, we can see that super in the constructor calls the constructor's parent class's constructor.

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.

See 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: SuperClass constructor
SubClass constructor
In the code, we only instantiate one subclass object. But from the execution result, the program does not run the constructor of the subclass at the beginning, but first executes the default constructor of the parent class, then execute the subclass construction method. 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.

Check instance 2 again:
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 we will first call the default constructor of its parent class when instantiating the subclass object, but its parent class does not have the default constructor, therefore, compilation fails.
Solution:
1. Add a display default constructor to the parent class.
2. Add a super (str) clause to the constructor of the subclass and add the first clause 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 () start
One-1
One-2
One-3
Two
We have implemented a Two object in the main method, but the program didn't call the Two constructor first when the Two object is in the instance, but initialized the member variable of the Two class first, the Two class has three member variables, all of which are One class objects. Therefore, 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 () start
One-3
One-1
One-2
Two-1
------------
One-1
One-2
Two-2
Conclusion: If a class has a static object, it will initialize the non-static object 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-3
One-1
One-2
Two-3
Test main () start
One-1
One-2
Two-1
------------
One-1
One-2
Two-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.

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.