本文目录导读:

我来通过几个实战案例,带你一步步实操Java对象创建的整个过程。
案例1:基础对象创建
定义学生类
public class Student {
// 属性
private String name;
private int age;
private String studentId;
// 无参构造器
public Student() {
System.out.println("无参构造器被调用");
}
// 有参构造器
public Student(String name, int age) {
this.name = name;
this.age = age;
System.out.println("有参构造器被调用");
}
// 全参构造器
public Student(String name, int age, String studentId) {
this.name = name;
this.age = age;
this.studentId = studentId;
System.out.println("全参构造器被调用");
}
// 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;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
// toString方法
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + ", studentId='" + studentId + "'}";
}
}
对象创建实操
public class ObjectCreationDemo {
public static void main(String[] args) {
// 方法1:使用new关键字(最常用)
System.out.println("=== 方式1:使用new关键字 ===");
Student student1 = new Student();
student1.setName("张三");
student1.setAge(20);
student1.setStudentId("2024001");
System.out.println("student1: " + student1);
// 方法2:使用有参构造器
System.out.println("\n=== 方式2:使用有参构造器 ===");
Student student2 = new Student("李四", 22);
student2.setStudentId("2024002");
System.out.println("student2: " + student2);
// 方法3:使用全参构造器
System.out.println("\n=== 方式3:使用全参构造器 ===");
Student student3 = new Student("王五", 21, "2024003");
System.out.println("student3: " + student3);
}
}
案例2:多种创建方式演示
public class AdvancedCreationDemo {
public static void main(String[] args) throws Exception {
// 方式4:使用Class类的newInstance()(已废弃,但了解)
System.out.println("=== 方式4:Class.newInstance() ===");
Student student4 = Student.class.newInstance();
student4.setName("赵六");
System.out.println("student4: " + student4);
// 方式5:使用Constructor的newInstance()
System.out.println("\n=== 方式5:Constructor.newInstance() ===");
Constructor<Student> constructor = Student.class.getConstructor(String.class, int.class);
Student student5 = constructor.newInstance("孙七", 23);
student5.setStudentId("2024005");
System.out.println("student5: " + student5);
// 方式6:使用clone()方法
System.out.println("\n=== 方式6:使用clone() ===");
Student original = new Student("周八", 24, "2024006");
Student student6 = (Student) original.clone();
System.out.println("student6 (克隆对象): " + student6);
}
}
注意:Student类需要实现Cloneable接口
public class Student implements Cloneable {
// ... 其他代码保持不变
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
案例3:使用Builder模式创建复杂对象
public class Employee {
private final String name; // 必填
private final int age; // 必填
private final String department; // 选填
private final String position; // 选填
private final double salary; // 选填
// 私有构造器
private Employee(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.department = builder.department;
this.position = builder.position;
this.salary = builder.salary;
}
// Builder静态内部类
public static class Builder {
private String name; // 必填
private int age; // 必填
private String department; // 选填
private String position; // 选填
private double salary; // 选填
// Builder构造器(传入必填参数)
public Builder(String name, int age) {
this.name = name;
this.age = age;
}
public Builder department(String department) {
this.department = department;
return this;
}
public Builder position(String position) {
this.position = position;
return this;
}
public Builder salary(double salary) {
this.salary = salary;
return this;
}
public Employee build() {
return new Employee(this);
}
}
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age +
", department='" + department + "', position='" + position +
"', salary=" + salary + "}";
}
}
使用Builder模式
public class BuilderPatternDemo {
public static void main(String[] args) {
// 链式调用创建对象
Employee employee = new Employee.Builder("张三", 30)
.department("技术部")
.position("高级工程师")
.salary(25000.0)
.build();
System.out.println("Builder创建的对象: " + employee);
// 只设置部分属性
Employee employee2 = new Employee.Builder("李四", 25)
.department("市场部")
.build();
System.out.println("简化创建: " + employee2);
}
}
案例4:模拟对象创建过程
public class ObjectLifecycleDemo {
public static class Person {
private static int counter = 0; // 静态变量
private String name;
// 静态代码块(类加载时执行)
static {
System.out.println("1. 静态代码块执行");
}
// 实例代码块(每次创建对象时执行)
{
System.out.println("2. 实例代码块执行");
}
// 构造器
public Person(String name) {
this.name = name;
counter++;
System.out.println("3. 构造器执行,当前创建第" + counter + "个对象");
}
public void showInfo() {
System.out.println("姓名: " + name);
}
}
public static void main(String[] args) {
System.out.println("开始创建第一个对象:");
Person p1 = new Person("张三");
p1.showInfo();
System.out.println("\n开始创建第二个对象:");
Person p2 = new Person("李四");
p2.showInfo();
System.out.println("\n开始创建第三个对象:");
Person p3 = new Person("王五");
p3.showInfo();
}
}
案例5:实际项目中的对象创建
public class PracticalCreationDemo {
// 模拟从数据库读取用户数据
public static class User {
private Long id;
private String username;
private String email;
private LocalDateTime createTime;
// 使用静态工厂方法
public static User createUser(String username, String email) {
User user = new User();
user.setUsername(username);
user.setEmail(email);
user.setCreateTime(LocalDateTime.now());
return user;
}
// 从Map转换
public static User fromMap(Map<String, Object> map) {
User user = new User();
user.setId((Long) map.get("id"));
user.setUsername((String) map.get("username"));
user.setEmail((String) map.get("email"));
user.setCreateTime((LocalDateTime) map.get("create_time"));
return user;
}
// Getter和Setter
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public LocalDateTime getCreateTime() { return createTime; }
public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; }
@Override
public String toString() {
return "User{id=" + id + ", username='" + username + "', email='" + email + "'}";
}
}
public static void main(String[] args) {
// 实际场景1:创建新用户
System.out.println("=== 场景1:创建新用户 ===");
User newUser = User.createUser("john_doe", "john@example.com");
System.out.println("新用户: " + newUser);
// 实际场景2:从数据转换
System.out.println("\n=== 场景2:从Map转换 ===");
Map<String, Object> userMap = new HashMap<>();
userMap.put("id", 1001L);
userMap.put("username", "admin");
userMap.put("email", "admin@example.com");
userMap.put("create_time", LocalDateTime.now());
User fromDb = User.fromMap(userMap);
System.out.println("数据库用户: " + fromDb);
// 实际场景3:使用Lombok(需要添加依赖)
// @Data注解自动生成Getter/Setter/toString等
System.out.println("\n=== 场景3:使用Lombok简化 ===");
// 如果使用Lombok,类可以简化为:
// @Data
// @Builder
// public class Product {
// private Long id;
// private String name;
// private Double price;
// }
}
}
运行建议
- 按顺序运行案例:从最简单的案例1开始,逐步深入
- 添加输出日志:在关键位置添加System.out.println观察执行顺序
- 使用IDE调试:在构造器、方法调用处设置断点,观察对象创建过程
- 修改代码测试:改变构造器参数、添加新属性等,观察影响
这些案例覆盖了Java对象创建的主要方式,建议你实际编码运行,观察输出结果,加深理解。