The more instance fields you have, the more redundant your code becomes. The class has a constructor, which uses a special method that is automatically called after instantiating it with new. Since the constructor is a special method, the definition method is fixed. ① Make the constructor name the same as the class name ② Do not write the return value (do not write void) [Example] This time, I will make it a person.
Person.java
class class name{
name of the class() { //constructor~
//Describe the process you want to perform when creating an instance
} //~constructor
}
[Example]
Main.java
class Main {
public static void main(String[] args) {
Person person1 = new Person();
Person person2 = new Person();
}
}
Person.java
class Person {
Person() {
System.out.println("Good morning");
}
}
Next, when creating an instance, pass the value you want to set in the instance field as an argument and set it in the constructor. You can use the instance with ** this **. [Example]
MAin.java
class Main {
public static void main(String[] args) {
Person person1 = new Person("Sato");
person1.hello();
Person person2 = new Person("Suzuki");
person2.hello();
}
}
Person.java
class Person {
public String name;
Person(String name) { //I'm trying to get the constructor to accept an argument of type String
System.out.println("Good morning");
this.name = name; //Setting a value for the instance field name
}
public void hello() {
System.out.println("I" + this.name + "is");
}
}
In the above, the Sato part of "new Person (" Sato ");" is the name of "Person (String name)" of Person.java is Sato (Suzuki), and the right side of "this.name = name;" It feels like Sato (Suzuki) is included in this.name from the name of.
If the contents of the constructor are duplicated, you can call another constructor from the constructor by using "this ()". this () is a special method for calling the constructor, and you can also pass arguments to (). this can only be called at the beginning of the constructor.
Recommended Posts