① The method name is exactly the same as the class name (2) The return value is not described in the method declaration (void is also useless)
public class Hero {
  String name;
  int hp;
  public Hero() {   //Definition of contrast
    this.hp = 100;  //Initialize hp field with 100
  }
}
Method that wrote the process that is automatically executed immediately after being new
public class Main {
  public static void main(String[] args) {
    Hero h = new Hero();      //100 is assigned to HP at the same time as instant generation
    h.hp = 100;               //I do not need
    System.out.println(h.hp); //Is displayed as 100
  }
}
public class Hero {
  String name;
  int hp;
  public Hero(String name) {   //Receives one string as an argument
    this.hp = 100;             //Initialize hp field with 100
    this.name = name;          //Initialize the name field with the value of the argument
  }
}
public class Main {
  public static void main(String[] args) {
    Hero h = new Hero("Brave");      //After the instant is generated, the JVM automatically executes the constructor as an argument."Brave"Is used
    System.out.println(h.hp);   //Is displayed as 100
    System.out.println(h.name); //Displayed as hero
  }
}
public class Hero {
  String name;
  int hp;
  public Hero(String name) {   //Constrasta ①
    this.name = name;          
  }
  public Hero() {              //Constructor ②
    this.name = "Brave 2"        //"Brave 2"The set
  }
}
public class Main {
  public static void main(String[] args) {
    Hero h = new Hero("Brave");      //Since there is a string argument, the constructor ① is called.
    System.out.println(h.name);    //Displayed as hero
    Hero h2 = new Hero();          //Constructor ② is called because there are no arguments
    System.out.println(h2.name);   //Displayed as Hero 2
  }
}
        Recommended Posts