根据前面章节定义的Cat类,现在Cat类中添加带参的Cat方法,注意参数名不能和要赋值的变量名相同:
public Cat(String newName, int newMonth, double newWeight, String newSpecies){
name = newName;
month = newMonth;
weight = newWeight;
species = newSpecies;
}
进行传参:
package java_animal;
public class CatTest {
public static void main(String[] args) {
Cat one = new Cat("花花", 2, 1000, "英国短毛猫");
System.out.println("昵称:"+one.name);
System.out.println("年龄:"+one.month);
System.out.println("体重:"+one.weight);
System.out.println("品种:"+one.species);
//one.run(one.name);
}
}
输出:
昵称:花花
年龄:2
体重:1000.0
品种:英国短毛猫
下一节讲关于this关键字的用法。