How to use JAVA construction method?

Example 1: what is the construction method?
Method name is the same as class name (including case)
No return type
When an object is instantiated, the construction method must be invoked.
package com.ty.servlet;

public class Dawei {
String name;

    float hp;
 
    float armor;
 
    int moveSpeed;
 
    // Method name is the same as class name (including case)
    // No return type
    public Dawei() {
        System.out.println("When an object is instantiated, the construction method must be invoked.");
    }
     
    public static void main(String[] args) {
        //When an object is instantiated, the construction method must be invoked.
        Dawei h = new Dawei();
    }

}

Example 2: Implicit construction method
The construction method of Hero class is
public Hero(){
}
This parameterless construction method, if not written, will default to provide a
package com.ty.servlet;

public class Dawei {
String name; / / name

    float hp; 
     
    float armor; 
     
    int moveSpeed; 
     
    //This parameterized construction method, if not written,
    //By default, an argument-free construction method is provided
    //  public Dawei(){ 
    //      System.out.println("Call Dawei's Construction Method");
    //  }
 
    public static void main(String[] args) {
        Dawei garen =  new Dawei();
        garen.name = "Small case";
        garen.hp = 616.28f;
        garen.armor = 27.536f;
        garen.moveSpeed = 350;
         
        Dawei teemo =  new Dawei();
        teemo.name = "Small graph";
        teemo.hp = 383f;
        teemo.armor = 14f;
        teemo.moveSpeed = 330;
    }  

}
Example 3: Overload of construction methods
Like ordinary methods, construction methods can also be overloaded
package com.ty.servlet;

public class Dawei {
String name; / / name

float hp; 
   
float armor; 
   
int moveSpeed; 
   
//Constructing Method with One Parameter
public Dawei(String Daweiname){ 
    name = Daweiname;
}
 
//Construction Method with Two Parameters
public Dawei(String Daweiname,float Daweihp){ 
    name = Daweiname;
    hp = Daweihp;
}
   
public static void main(String[] args) {
    Dawei garen =  new Dawei("Little Gar"); 
    Dawei teemo =  new Dawei("Tai Mo",383);
}

}

Posted by westair on Thu, 03 Oct 2019 04:05:35 -0700