this. field name = argument;
//Argument name in the constructor/Set age to the corresponding field
public class Person {
public String name;
public int age;
//constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String show() {
return String.format("%s(%d).", this.name, this.age);
}
}
ConstBasic.java
public class ConstBasic {
public static void main(String[] args) {
var p = new Person("Yamada Taro", 30);
System.out.println(p.show()); //I'm Taro Yamada (30 years old).
}
}
public class MyClass{
}
public class MyClass{
public MyClass(){
}
}
Person.java
public class Person {
public String name;
public int age;
//constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
//Constructor call
this("Hello Kitty", 46);
}
public void show() {
System.out.printf("%s(%d).\n", this.name, this.age);
}
}
ConstructorBasic.java
public class ConstructorBasic {
public static void main(String[] args) {
var p = new Person();
p.show(); //Hello Kitty (46 years old).
}
}
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
public class Person {
public String name;
public int age;
public LocalDateTime updated;
//Initialization block
{
this.updated = LocalDateTime.now();
}
//First and last name,Initialize from birthday
public Person(String firstName, String lastName, LocalDate birth) {
this.name = lastName + " " + firstName;
this.age = Period.between(birth, LocalDate.now()).getYears();
}
//name,Initialize from age
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
var fc = FactoryClass.getInstance();
public class FactoryClass {
//private constructor
private FactoryClass() {
System.out.println("Factory!!");
}
//Factory method
public static FactoryClass getInstance() {
return new FactoryClass();
}
}
Recommended Posts