chap7学习内容

chap7学习内容

一、什么是类和对象

概念

说明

类(Class)

模板、图纸

对象(Object)

根据类创建的具体实例

类是抽象的,对象是具体的


二、类的定义

1️⃣ 类的基本结构

class 类名 { 属性(成员变量) 方法(成员方法) }

2️⃣ 示例:Student 类

class Student { String name; int age; double score; public void study() { System.out.println("学习"); } }

三、对象的创建与使用

1️⃣ 创建对象

Student s = new Student();

2️⃣ 访问属性和方法

s.name = "张三"; s.age = 23; s.score = 99.0; System.out.println(s.name + "-" + s.age + "-" + s.score); s.study();

规则:

  • 对象.属性
  • 对象.方法()

四、构造方法

1️⃣ 什么是构造方法

构造方法 = 创建对象时自动调用的方法

特点:

  • 方法名 必须和类名相同
  • 没有返回值
  • 不写时,系统会提供 默认无参构造

2️⃣ 无参构造

public Student() { System.out.println("无参构造..."); }

调用方式:

Student s = new Student();

3️⃣ 有参构造

public Student(String name, int age, double score) { this.name = name; this.age = age; this.score = score; }

创建对象:

Student s = new Student("李四", 20, 88.5);

4️⃣ 构造方法重载

public Dog() {} public Dog(int age) {} public Dog(String name, int age, char sex) {}

好处:

  • 创建对象更灵活
  • 代码更简洁

五、this 关键字

1️⃣ this 的作用

用法

说明

this.属性

区分成员变量和局部变量

this()

调用本类其他构造方法


2️⃣ this 区分同名变量

public void study() { int age = 50; System.out.println(this.age); // 成员变量 System.out.println(age); // 局部变量 }

3️⃣ this() 调用构造方法

public Student(String name, int age, double score) { this(); // 必须写在第一行 this.name = name; this.age = age; this.score = score; }

注意:

  • this()只能在构造方法中使用
  • 必须是第一条语句

六、方法重载

1️⃣ 什么是方法重载

方法名相同,参数不同

判断标准:

项目

是否影响重载

参数个数不同

参数类型不同

参数顺序不同

返回值不同

修饰符不同


2️⃣ 示例

public void ma() {} public void ma(int a) {} public void ma(String str) {} public void ma(int a, int b) {}

调用时:

mc.ma(); // ma() mc.ma(""); // ma(String) mc.ma(2, 90); // ma(int, int)

JVM 根据 参数类型和数量 自动匹配方法


七、对象的内存与引用

1️⃣ 多个引用指向同一对象

Student s4 = null; s4 = s2; s4.age = 60;

结果:

  • s2.ages4.age同时改变

原因:

s2 和 s4 指向堆中同一个对象


2️⃣ null 的含义

Student s5 = null;

空指针异常:

System.out.println(s5.age); // NullPointerException

规则:

  • null 对象 不能访问属性或方法