Java 类与对象
Java 是面向对象的编程语言,类和对象是 Java 的核心概念。
什么是类和对象
类(Class)
类是对具有相同属性和行为的一组对象的抽象描述,是创建对象的模板。
// 类的定义
public class Person {
// 属性(成员变量)
private String name;
private int age;
// 构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 方法(成员方法)
public void introduce() {
System.out.println("我是 " + name + ",今年 " + age + " 岁");
}
// Getter 和 Setter 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}对象(Object)
对象是类的实例,是类的具体实现。
public class ObjectExample {
public static void main(String[] args) {
// 创建对象:使用 new 关键字
Person person1 = new Person("张三", 25);
Person person2 = new Person("李四", 30);
// 调用对象的方法
person1.introduce(); // 输出:我是 张三,今年 25 岁
person2.introduce(); // 输出:我是 李四,今年 30 岁
// 访问对象的属性(通过方法)
System.out.println(person1.getName()); // 输出:张三
System.out.println(person1.getAge()); // 输出:25
}
}类的组成
成员变量(属性)
public class Student {
// 实例变量:每个对象都有自己的一份
private String name;
private int age;
// 类变量(静态变量):所有对象共享
private static int totalStudents = 0;
// 常量:使用 final 关键字
private static final String SCHOOL_NAME = "XX大学";
public Student(String name, int age) {
this.name = name;
this.age = age;
totalStudents++; // 每创建一个学生,总数加1
}
public static int getTotalStudents() {
return totalStudents;
}
}构造方法
public class Car {
private String brand;
private String color;
private int price;
// 无参构造方法(默认构造方法)
public Car() {
this.brand = "未知";
this.color = "未知";
this.price = 0;
}
// 有参构造方法
public Car(String brand, String color, int price) {
this.brand = brand;
this.color = color;
this.price = price;
}
// 构造方法重载
public Car(String brand) {
this.brand = brand;
this.color = "白色";
this.price = 100000;
}
public void display() {
System.out.println("品牌:" + brand + ",颜色:" + color + ",价格:" + price);
}
}成员方法
public class Calculator {
// 实例方法:需要对象调用
public int add(int a, int b) {
return a + b;
}
// 静态方法:可以直接通过类名调用
public static int multiply(int a, int b) {
return a * b;
}
// 方法可以访问实例变量
private int result = 0;
public void accumulate(int value) {
result += value;
}
public int getResult() {
return result;
}
}this 关键字
public class ThisExample {
private String name;
private int age;
public ThisExample(String name, int age) {
// this 指向当前对象
// this.name 表示当前对象的 name 属性
// name 表示参数 name
this.name = name; // 将参数赋值给当前对象的属性
this.age = age;
}
public void setName(String name) {
this.name = name; // 区分参数和成员变量
}
// this 可以调用其他构造方法
public ThisExample() {
this("默认名称", 0); // 调用另一个构造方法
}
// this 可以返回当前对象
public ThisExample setAge(int age) {
this.age = age;
return this; // 返回当前对象,支持链式调用
}
}访问修饰符
public class AccessModifiers {
// public:公共的,任何地方都可以访问
public String publicField = "公共字段";
// private:私有的,只能在本类中访问
private String privateField = "私有字段";
// protected:受保护的,本类、同包、子类可以访问
protected String protectedField = "受保护字段";
// 默认(包访问):同包可以访问
String defaultField = "默认字段";
// 方法也有访问修饰符
public void publicMethod() {
System.out.println("公共方法");
}
private void privateMethod() {
System.out.println("私有方法");
}
protected void protectedMethod() {
System.out.println("受保护方法");
}
void defaultMethod() {
System.out.println("默认方法");
}
}封装
// 封装:将数据和对数据的操作封装在一起
// 通过访问修饰符控制访问权限
public class BankAccount {
// 私有属性:外部不能直接访问
private String accountNumber;
private double balance;
// 构造方法
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
// 通过方法设置余额,可以添加验证逻辑
setBalance(initialBalance);
}
// Getter 方法:获取余额
public double getBalance() {
return balance;
}
// Setter 方法:设置余额(添加验证)
public void setBalance(double balance) {
if (balance < 0) {
System.out.println("余额不能为负数");
return;
}
this.balance = balance;
}
// 存款方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("存款成功,当前余额:" + balance);
} else {
System.out.println("存款金额必须大于0");
}
}
// 取款方法
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("取款成功,当前余额:" + balance);
} else {
System.out.println("取款失败:余额不足或金额无效");
}
}
public String getAccountNumber() {
return accountNumber;
}
}实际应用示例
示例1:学生管理系统
public class Student {
private String id;
private String name;
private int age;
private double score;
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
this.score = 0.0;
}
public void setScore(double score) {
if (score >= 0 && score <= 100) {
this.score = score;
} else {
System.out.println("分数必须在 0-100 之间");
}
}
public String getGrade() {
if (score >= 90) return "优秀";
if (score >= 80) return "良好";
if (score >= 60) return "及格";
return "不及格";
}
public void display() {
System.out.println("学号:" + id);
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
System.out.println("分数:" + score);
System.out.println("等级:" + getGrade());
}
// Getter 方法
public String getId() { return id; }
public String getName() { return name; }
public int getAge() { return age; }
public double getScore() { return score; }
}示例2:图书类
public class Book {
private String isbn;
private String title;
private String author;
private double price;
private int stock; // 库存
public Book(String isbn, String title, String author, double price, int stock) {
this.isbn = isbn;
this.title = title;
this.author = author;
this.price = price;
this.stock = stock;
}
// 借书
public boolean borrow() {
if (stock > 0) {
stock--;
System.out.println("借书成功,剩余库存:" + stock);
return true;
} else {
System.out.println("库存不足,无法借阅");
return false;
}
}
// 还书
public void returnBook() {
stock++;
System.out.println("还书成功,当前库存:" + stock);
}
// 显示信息
public void display() {
System.out.println("ISBN:" + isbn);
System.out.println("书名:" + title);
System.out.println("作者:" + author);
System.out.println("价格:" + price);
System.out.println("库存:" + stock);
}
// Getter 和 Setter
public String getIsbn() { return isbn; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public int getStock() { return stock; }
}总结
类和对象是 Java 面向对象编程的基础:
- 类:对象的模板,定义属性和方法
- 对象:类的实例,具体的实体
- 封装:将数据和方法封装在一起,控制访问权限
- 访问修饰符:控制类成员的访问范围
- this 关键字:指向当前对象
- 构造方法:用于创建和初始化对象
掌握类和对象是学习 Java 面向对象编程的第一步。
相关链接: