CS61B 课程笔记(Lecture 02)

关键概念:在Java中定义和使用类


1. 基本的类与对象创建

在Java中,类是创建对象的蓝图。类可以包含数据(变量)和行为(方法)。

  • 类的声明

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public class Dog {
    public int weightInPounds;

    public void makeNoise() {
    if (weightInPounds < 10) {
    System.out.println("yipyipyip!");
    } else if (weightInPounds < 30) {
    System.out.println("bark. bark.");
    } else {
    System.out.println("woof!");
    }
    }
    }

    Dog类中,weightInPounds是一个实例变量makeNoise是一个实例方法

2. 实例方法与对象实例化

  • 实例化:要根据类创建对象,使用new关键字:

    1
    2
    3
    Dog d = new Dog();
    d.weightInPounds = 20;
    d.makeNoise();

    这创建了一个Dog对象d,并为weightInPounds赋值。

  • 点符号:要访问对象的方法或变量,使用点符号(d.makeNoise())。

3. 构造器

构造器在对象创建时初始化对象的状态。如果没有提供构造器,Java将使用默认构造器。

  • 自定义构造器

    1
    2
    3
    public Dog(int w) {
    weightInPounds = w;
    }

    然后可以创建一个具有特定重量的Dog对象:

    1
    2
    Dog d = new Dog(20);
    d.makeNoise();

4. 静态方法与实例方法

  • 静态方法:与类本身关联,而不是与特定对象关联。它们使用类名调用。

    1
    2
    3
    4
    5
    6
    7
    public static Dog maxDog(Dog d1, Dog d2) {
    return (d1.weightInPounds > d2.weightInPounds) ? d1 : d2;
    }

    Dog d1 = new Dog(15);
    Dog d2 = new Dog(100);
    Dog.maxDog(d1, d2);
  • 实例方法:需要类的一个实例来调用。它们可以访问实例变量。

    1
    2
    3
    public Dog maxDog(Dog d2) {
    return (this.weightInPounds > d2.weightInPounds) ? this : d2;
    }

5. 静态变量

  • 静态变量:在所有类的实例之间共享,属于类,而不是特定的对象。

    1
    public static String binomen = "Canis familiaris";

6. 对象数组

要创建一个对象数组,首先声明数组,然后为每个元素实例化对象:

1
2
3
4
5
Dog[] dogs = new Dog[2];
dogs[0] = new Dog(8);
dogs[1] = new Dog(20);

dogs[0].makeNoise(); // 输出:"yipyipyip!"

7. 命令行参数

main方法可以接受命令行参数,它们作为String数组传递:

1
2
3
4
5
public class ArgsDemo {
public static void main(String[] args) {
System.out.println(args[0]);
}
}

执行java ArgsDemo Hello World将输出Hello


总结

  • :用于创建对象的模板,包含实例变量和方法。
  • 实例方法:对特定对象操作,并能访问实例变量。
  • 静态方法:对类本身操作,不能访问实例变量。
  • 构造器:用于初始化对象的特殊方法。
  • 数组:可以包含多个对象,每个元素都需要单独实例化。