java參數(shù)設置默認值,只傳遞想傳的參數(shù)
public class Main {
public static void main(String[] args) {
Child child = new Child();
Child c1 = child.newChild(27, 80);
String r1 = c1.toString();
System.out.println(r1);
Child c2 = child.newChildWithAge(22);
String r2 = c2.toString();
System.out.println(r2);
Child c3 = child.newChildWithWeight(100);
String r3 = c3.toString();
System.out.println(r3);
}
}
class Child {
int age = 10;
int weight = 30;
public static Child newChild(int age, int weight) {
Child child = new Child();
child.weight = weight;
child.age = age;
return child;
}
public static Child newChildWithWeight(int weight) {
Child child = new Child();
child.weight = weight;
return child;
}
public static Child newChildWithAge(int age) {
Child child = new Child();
child.age = age;
return child;
}
@Override
public String toString() {
return "Child{" +
"age=" + age +
", weight=" + weight +
'}';
}
}