面向对象基础
类与对象
类的定义
java
public class Person {
// 成员变量(属性)
private String name;
private int age;
// 构造方法
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 成员方法
public void sayHello() {
System.out.println("你好,我是" + name);
}
// 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) {
if (age > 0) {
this.age = age;
}
}
}创建对象
java
public class PersonDemo {
public static void main(String[] args) {
// 使用new关键字创建对象
Person person1 = new Person();
person1.setName("张三");
person1.setAge(25);
person1.sayHello();
// 使用构造方法创建对象
Person person2 = new Person("李四", 30);
person2.sayHello();
}
}构造方法
构造方法特点
- 方法名与类名相同
- 没有返回值类型
- 可以重载
- 用于初始化对象
java
public class Student {
private String name;
private int age;
private String school;
// 无参构造
public Student() {
this("未知", 0, "未知学校");
}
// 带参构造
public Student(String name, int age) {
this(name, age, "默认学校");
}
// 全参构造
public Student(String name, int age, String school) {
this.name = name;
this.age = age;
this.school = school;
}
}默认构造方法
java
public class DefaultConstructor {
// 如果没有定义任何构造方法
// 编译器会自动生成无参构造方法
}
// 等价于
public class DefaultConstructor {
public DefaultConstructor() {
}
}this关键字
引用当前对象
java
public class ThisDemo {
private String name;
public ThisDemo(String name) {
// 区分成员变量和局部变量
this.name = name;
}
public void show() {
System.out.println(this.name);
}
// 调用其他构造方法
public ThisDemo() {
this("默认名称"); // 必须放在第一行
}
// 返回当前对象
public ThisDemo setName(String name) {
this.name = name;
return this; // 链式调用
}
}this用法
| 用法 | 说明 | 示例 |
|---|---|---|
this.变量 | 区分成员变量和局部变量 | this.name = name |
this.方法() | 调用当前对象的方法 | this.show() |
this() | 调用其他构造方法 | this("default") |
return this | 返回当前对象 | 用于链式调用 |
封装
访问修饰符
| 修饰符 | 同一类 | 同一包 | 子类 | 其他 |
|---|---|---|---|---|
public | ✓ | ✓ | ✓ | ✓ |
protected | ✓ | ✓ | ✓ | ✗ |
| 默认 | ✓ | ✓ | ✗ | ✗ |
private | ✓ | ✗ | ✗ | ✗ |
封装示例
java
public class BankAccount {
// 私有属性
private String accountNumber;
private double balance;
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0;
}
// 公共方法访问私有属性
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("存款成功:" + amount);
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("取款成功:" + amount);
} else {
System.out.println("取款失败");
}
}
}static关键字
静态变量
java
public class Counter {
// 静态变量(类变量),所有对象共享
private static int count = 0;
// 实例变量
private int id;
public Counter() {
count++;
this.id = count;
}
public static int getCount() {
return count;
}
public int getId() {
return id;
}
}
// 使用
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount()); // 2
System.out.println(c1.getId()); // 1
System.out.println(c2.getId()); // 2静态方法
java
public class MathUtils {
// 静态方法,可以直接通过类名调用
public static int add(int a, int b) {
return a + b;
}
public static int max(int a, int b) {
return a > b ? a : b;
}
}
// 使用
int sum = MathUtils.add(1, 2);
int maximum = MathUtils.max(10, 20);静态代码块
java
public class Database {
private static Connection connection;
// 静态代码块,类加载时执行一次
static {
System.out.println("初始化数据库连接...");
// connection = DriverManager.getConnection(...);
}
public static Connection getConnection() {
return connection;
}
}静态导入
java
import static java.lang.Math.*;
public class StaticImport {
public static void main(String[] args) {
// 直接使用Math类的方法
System.out.println(PI); // 3.14159...
System.out.println(sqrt(16)); // 4.0
System.out.println(abs(-10)); // 10
}
}代码块
普通代码块
java
public class CodeBlock {
{
// 构造代码块,每次创建对象时执行
System.out.println("构造代码块");
}
public CodeBlock() {
System.out.println("构造方法");
}
}执行顺序
java
public class OrderDemo {
private static String staticVar = initStaticVar();
private String instanceVar = initInstanceVar();
static {
System.out.println("1. 静态代码块");
}
{
System.out.println("3. 构造代码块");
}
public OrderDemo() {
System.out.println("4. 构造方法");
}
private static String initStaticVar() {
System.out.println("0. 静态变量初始化");
return "static";
}
private String initInstanceVar() {
System.out.println("2. 实例变量初始化");
return "instance";
}
public static void main(String[] args) {
new OrderDemo();
}
}
// 输出顺序: 0 → 1 → 2 → 3 → 4完整示例
java
public class Book {
// 静态变量
private static int totalCount = 0;
// 实例变量
private String title;
private String author;
private double price;
// 静态代码块
static {
System.out.println("图书管理系统初始化...");
}
// 构造代码块
{
totalCount++;
System.out.println("创建第 " + totalCount + " 本书");
}
// 构造方法
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
// getter/setter
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
// 实例方法
public void display() {
System.out.printf("《%s》- %s - ¥%.2f%n", title, author, price);
}
// 静态方法
public static int getTotalCount() {
return totalCount;
}
}