Java 中最基本的单元,理解如何定义类、创建对象
在 Java 中,使用 class 关键字来定义类。类包含成员变量(属性)和成员方法(行为)。
public class Student {
// 成员变量(属性)—— 描述对象的特征
String name;
int age;
int score;
// 构造方法:创建对象时自动调用,用于初始化对象
public Student(String name, int age) {
this.name = name;
this.age = age;
this.score = 0;
}
// 成员方法(行为)—— 描述对象能做什么
public void study() {
System.out.println(name + "正在学习...");
score += 5;
}
public void introduce() {
System.out.println("我叫" + name + ",今年" + age + "岁,成绩是" + score);
}
}
类是抽象的模板,对象是具体的实例。使用 new 关键字创建对象。
public class Main {
public static void main(String[] args) {
// 创建对象(使用 new 关键字 + 构造方法)
Student student1 = new Student("张三", 20);
Student student2 = new Student("李四", 19);
// 调用方法
student1.introduce(); // 我叫张三,今年20岁,成绩是0
student1.study(); // 张三正在学习...
student1.introduce(); // 成绩变成5
student2.introduce(); // 我叫李四,今年19岁,成绩是0
}
}
this 表示当前对象。当成员变量和方法参数同名时,需要用 this.变量名 来区分。例如 this.name = name 中,左边的 this.name 是成员变量,右边的 name 是参数。