Lec2
构造器 Constructer
public Dog(int w) {
weightInPounds = w;
}
- 名字和类名完全一样
- 没有返回类型(连 void 都没有)
- 在
new一个对象时自动执行,负责初始化数据 - 类比 C:相当于
malloc+ 初始化变量,Java 自动帮你完成内存分配
Dog d = new Dog(15);
// ↑
// 15 传给参数 w
// 执行 weightInPounds = 15
构造器的几种写法
// 1. 无参构造器
public Dog() {
weightInPounds = 0;
}
// 2. 有参构造器
public Dog(int w) {
weightInPounds = w;
}
// 3. 多个参数
public Dog(int w, String name) {
weightInPounds = w;
this.name = name;
}
// 4. 重载:一个类可以有多个构造器
Dog d1 = new Dog(); // 自动选择无参构造器
Dog d2 = new Dog(15); // 自动选择有参构造器
实例方法
public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yip!");
}
else if (weightInPounds < 30) {
System.out.println("bark!");
}
else {
System.out.println("woooof!");
}
}
- 没有
static关键字 - 必须有一个具体的对象才能调用
- 方法内部可以访问
this(当前对象的数据) - 叫声取决于这个对象自己的
weightInPounds
d1.makeNoise(); // d1 = 15磅 → "bark!"
d2.makeNoise(); // d2 = 100磅 → "woooof!"
// 同一个方法,不同对象,结果不同
静态方法
public static Dog maxDog(Dog d1, Dog d2) {
if (d1.weightInPounds > d2.weightInPounds) {
return d1;
}
return d2;
}
- 有
static关键字 - 不属于任何一个具体对象,属于 Dog 这个类本身
- 用类名调用,不需要先创建对象
Dog.maxDog(d1, d2);

浙公网安备 33010602011771号