Java 构造函数相关应用技巧

Java 构造函数应用技巧全解析

Java 构造函数的基本概念

构造函数是类中用于初始化对象的特殊方法,名称必须与类名相同且无返回值。当创建对象时,构造函数会被自动调用。

public class Car {
    private String model;

    // 构造函数
    public Car(String model) {
        this.model = model;
    }
}

默认构造函数

如果未显式定义构造函数,Java 会提供默认的无参构造函数。若定义了任何构造函数,默认构造函数不再自动生成。

public class Book {
    private String title;

    // 默认构造函数(未显式定义时存在)
    public Book() {
        title = "Unknown";
    }
}

构造函数重载

通过参数列表的不同,可以定义多个构造函数实现不同初始化逻辑。

public class Student {
    private String name;
    private int age;

    // 无参构造函数
    public Student() {
        name = "Default";
        age = 18;
    }

    // 带参数的构造函数
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

构造函数调用其他构造函数

使用 this() 可以在一个构造函数中调用同类其他构造函数,需置于第一行。

public class Rectangle {
    private int width;
    private int height;

    // 无参构造函数调用带参构造函数
    public Rectangle() {
        this(10, 10); // 默认宽度和高度
    }

    // 带参构造函数
    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }
}

私有构造函数的应用

通过私有构造函数限制实例化,常用于单例模式或工具类。

public class Singleton {
    private static Singleton instance;

    // 私有构造函数
    private Singleton() {}

    // 提供全局访问点
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

构造函数与继承

子类构造函数默认调用父类无参构造函数 super(),若父类无无参构造函数,需显式调用。

class Animal {
    private String type;

    public Animal(String type) {
        this.type = type;
    }
}

class Dog extends Animal {
    private String breed;

    public Dog(String type, String breed) {
        super(type); // 必须显式调用父类构造函数
        this.breed = breed;
    }
}

初始化块与构造函数

静态初始化块和实例初始化块会在构造函数之前执行,可用于复杂初始化逻辑。

public class Example {
    private static int staticVar;
    private int instanceVar;

    // 静态初始化块
    static {
        staticVar = 100;
    }

    // 实例初始化块
    {
        instanceVar = 50;
    }

    public Example() {
        System.out.println("Constructor called");
    }
}

构造函数的异常处理

构造函数中可抛出异常,但需注意对象可能未完全初始化。

public class DatabaseConnection {
    private String connection;

    public DatabaseConnection(String url) throws IOException {
        if (url == null) {
            throw new IllegalArgumentException("URL cannot be null");
        }
        this.connection = establishConnection(url);
    }

    private String establishConnection(String url) throws IOException {
        // 模拟连接逻辑
        if (url.startsWith("invalid")) {
            throw new IOException("Connection failed");
        }
        return "Connected to " + url;
    }
}

构造函数的性能优化

避免在构造函数中进行耗时操作(如 I/O 或网络请求),可延迟到方法中执行。

public class LazyInitialization {
    private HeavyResource resource;

    public HeavyResource getResource() {
        if (resource == null) {
            resource = new HeavyResource(); // 延迟初始化
        }
        return resource;
    }
}

class HeavyResource {
    public HeavyResource() {
        // 模拟耗时操作
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值