第一部分:属性(成员变量)
理解Java中属性的定义、分类和使用场景
学习目标
掌握属性的声明语法、作用域、初始值规则,理解实例变量与类变量的区别
1
属性的基本语法
[修饰符] 数据类型 属性名 [= 初始值];
public class Person {
// 实例变量(对象级别)
private String name;
private int age = 18; // 显式初始值
// 类变量(类级别,共享)
public static int count = 0;
// 常量
public static final String SPECIES = "Human";
}
2
属性初始化规则
数据类型 | 默认初始值 | 示例 |
---|---|---|
int | 0 | int age; // 默认为0 |
double | 0.0 | double height; // 默认为0.0 |
boolean | false | boolean married; // 默认为false |
引用类型 | null | String name; // 默认为null |
实例变量 vs 类变量
public class Student {
// 实例变量:每个对象独立
private String name;
private int age;
// 类变量:所有对象共享
private static String schoolName = "清华大学";
public static void main(String[] args) {
Student stu1 = new Student();
stu1.name = "张三";
Student stu2 = new Student();
stu2.name = "李四";
// 类变量共享
System.out.println(stu1.schoolName); // 清华大学
System.out.println(stu2.schoolName); // 清华大学
Student.schoolName = "北京大学";
System.out.println(stu1.schoolName); // 北京大学
}
}
第二部分:方法(成员函数)
深入理解Java方法的定义、调用和重载机制
学习目标
掌握方法的完整语法,理解参数传递机制,学会方法重载
1
方法基本语法
[修饰符] 返回类型 方法名([参数列表]) {
// 方法体
[return 返回值;]
}
2
实例方法示例
public class Calculator {
// 实例变量
private double lastResult;
// 无参无返回值方法
public void reset() {
lastResult = 0;
}
// 有参有返回值方法
public double add(double a, double b) {
lastResult = a + b;
return lastResult;
}
// 可变参数方法
public double sum(double... numbers) {
double total = 0;
for (double num : numbers) {
total += num;
}
return total;
}
// 类方法(静态方法)
public static int max(int a, int b) {
return (a > b) ? a : b;
}
}
参数传递机制
public class ParamTest {
public static void main(String[] args) {
int x = 10;
changePrimitive(x);
System.out.println(x); // 输出10,值传递
Person p = new Person("张三");
changeReference(p);
System.out.println(p.getName()); // 输出"李四",引用传递
}
public static void changePrimitive(int value) {
value = 20; // 不影响原值
}
public static void changeReference(Person person) {
person.setName("李四"); // 影响原对象
}
}
方法重载
public class PrintUtil {
// 重载方法:同名不同参
public void print(String s) {
System.out.println(s);
}
public void print(int i) {
System.out.println("整数:" + i);
}
public void print(String s, int times) {
for (int i = 0; i < times; i++) {
System.out.println(s);
}
}
public double area(double radius) { // 圆形面积
return Math.PI * radius * radius;
}
public double area(double length, double width) { // 矩形面积
return length * width;
}
}
第三部分:构造函数
掌握构造函数的定义、重载和调用链
学习目标
理解构造函数的作用,掌握构造重载,学会使用this关键字
1
构造函数基本特征
- 方法名必须与类名完全相同
- 没有返回类型(连void都没有)
- 可以重载(多个不同参数列表的构造函数)
- 如果未定义,系统提供默认无参构造
2
构造函数示例
public class Book {
private String title;
private String author;
private double price;
// 1. 无参构造函数
public Book() {
this("未知书名", "未知作者", 0.0); // 调用其他构造
}
// 2. 部分参数构造函数
public Book(String title, String author) {
this(title, author, 59.9); // 设置默认价格
}
// 3. 全参构造函数
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
}
构造函数调用链
使用this()调用其他构造函数时,必须是第一条语句
public class Employee {
private String name;
private int age;
private double salary;
public Employee() {
this("新员工"); // 调用Employee(String)
}
public Employee(String name) {
this(name, 25); // 调用Employee(String, int)
}
public Employee(String name, int age) {
this(name, age, 5000); // 调用全参构造
}
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
}
第四部分:访问控制修饰符
理解public、private、protected和默认访问权限的区别
访问权限对照表
修饰符 | 同类 | 同包 | 子类 | 其他包 |
---|---|---|---|---|
public | √ | √ | √ | √ |
protected | √ | √ | √ | × |
默认(无修饰符) | √ | √ | × | × |
private | √ | × | × | × |
实际应用示例
public class BankAccount {
private String accountNumber; // 私有:只能内部访问
private double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public double getBalance() { // 公有:外部可访问
return balance;
}
public void deposit(double amount) {
if (isValidAmount(amount)) {
balance += amount;
}
}
private boolean isValidAmount(double amount) { // 私有:内部工具方法
return amount > 0;
}
}
第五部分:常见错误与调试
总结属性和方法使用中的典型问题及解决方案
构造函数错误
错误示例:
public void Student() {} // 错误!返回类型使这变成了普通方法
正确写法:
public Student() {} // 正确!无返回类型
属性隐藏问题
错误示例:
public class Person {
private String name;
public Person(String name) {
name = name; // 错误!没有区分实例变量和参数
}
}
正确写法:
public class Person {
private String name;
public Person(String name) {
this.name = name; // 正确!使用this区分
}
}
方法重载错误
错误示例:
public void print(String s) {}
public int print(String s) {} // 错误!仅返回类型不同不构成重载
正确写法:
public void print(String s) {}
public void print(int i) {} // 正确!参数列表不同
第六部分:综合实战 - 学生管理系统
综合运用属性、方法和构造函数完成实际项目
1
需求分析
- 管理学生信息(学号、姓名、年龄、成绩)
- 支持添加、删除、查询学生
- 计算班级平均成绩
- 查找最高分学生
2
完整实现
public class StudentManager {
private static final int MAX_STUDENTS = 100;
private Student[] students;
private int count;
public StudentManager() {
students = new Student[MAX_STUDENTS];
count = 0;
}
public boolean addStudent(Student student) {
if (count < MAX_STUDENTS) {
students[count++] = student;
return true;
}
return false;
}
public double getAverageScore() {
if (count == 0) return 0;
double total = 0;
for (int i = 0; i < count; i++) {
total += students[i].getScore();
}
return total / count;
}
public Student getTopStudent() {
if (count == 0) return null;
Student top = students[0];
for (int i = 1; i < count; i++) {
if (students[i].getScore() > top.getScore()) {
top = students[i];
}
}
return top;
}
}
class Student {
private String studentId;
private String name;
private int age;
private double score;
public Student() {
this("0000", "无名氏", 0, 0);
}
public Student(String studentId, String name, int age) {
this(studentId, name, age, 0);
}
public Student(String studentId, String name, int age, double score) {
this.studentId = studentId;
this.name = name;
this.age = age;
this.score = score;
}
// getter和setter方法
public String getStudentId() { return studentId; }
public String getName() { return name; }
public double getScore() { return score; }
public void displayInfo() {
System.out.printf("学号:%s,姓名:%s,年龄:%d,成绩:%.1f%n",
studentId, name, age, score);
}
}
测试代码
public class TestStudentManager {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
// 添加学生
manager.addStudent(new Student("2024001", "张三", 20, 85.5));
manager.addStudent(new Student("2024002", "李四", 19, 92.0));
manager.addStudent(new Student("2024003", "王五", 21, 78.5));
// 显示统计信息
System.out.println("班级平均成绩:" + manager.getAverageScore());
Student top = manager.getTopStudent();
if (top != null) {
System.out.print("最高分学生:");
top.displayInfo();
}
}
}
班级平均成绩:85.3
最高分学生:学号:2024002,姓名:李四,年龄:19,成绩:92.0
学习总结
- 属性:定义对象状态,区分实例变量和类变量
- 方法:定义对象行为,支持重载实现多态
- 构造函数:对象初始化,支持重载和调用链
- 访问控制:通过修饰符实现封装,保护数据安全
- 最佳实践:属性私有、方法公有、构造函数多样化