实例化对象
- 案例:宠物猫类
package com.study.animal;
public class CatTest {
public static void main(String[] args) {
// 对象实例化
Cat one = new Cat();
// 测试
System.out.println("昵称" + one.name);
System.out.println("年龄" + one.month);
System.out.println("体重" + one.weight);
System.out.println("品种" + one.species);
one.run();
// one.Cat();
}
}
运行结果:
昵称null
年龄0
体重0.0
品种null
小猫吃鱼
小猫快跑
注:
类中成员属性定义后系统会自动赋初始值的,而类的方法中定义的局部变量是没有默认初始值的。
2. 方法重载
对run方法进行重载:
public void run(String name){
System.out.println(name+"快跑");
}
在主方法内进行测试:
package com.study.animal;
public class CatTest {
public static void main(String[] args) {
// 对象实例化
Cat one = new Cat();
// 测试
one.run();
one.name = "喵喵";
one.month = 2;
one.weight = 1000;
one.species = "英国短毛猫";
System.out.println("昵称:" + one.name);
System.out.println("年龄:" + one.month);
System.out.println("体重:" + one.weight);
System.out.println("品种:" + one.species);
one.run(one.name);
// one.Cat();
}
}
运行结果:
小猫吃鱼
小猫快跑
昵称:喵喵
年龄:2
体重:1000.0
品种:英国短毛猫
喵喵快跑