且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么Toast可以在没有new关键字的情况下实例化?

更新时间:2023-09-16 19:14:16

没有什么特别关于 Toast 这里。您只是调用一个静态方法来创建一个实例(或者可能重用现有实例 - 它是一个实现细节)。这是一个你会在整个地方看到的模式 - 例如 Calendar.getInstance()。有时您可以调用构造函数,有时您可以通过静态方法创建实例。

There's nothing special about Toast here. You're just calling a static method which creates an instance (or could possibly reuse an existing one - it's an implementation detail). This is a pattern you'll see all over the place - Calendar.getInstance(), for example. Sometimes you can call the constructor instead, sometimes you can only create an instance via a static method.

除非在某些工艺下进行在实现中,很可能某处会对构造函数进行调用。这是一个简单的例子:

Unless something craft is going on under the hood, it's likely that somewhere in the implementation there'll be a call to a constructor. Here's a trivial example:

public final class CreateViaMethod {
    private final String name;

    private CreateViaMethod(String name) {
        this.name = name;
    }

    public static CreateViaMethod newInstance(String name) {
        return new CreateViaMethod(name);
    }
}

API设计师有多种原因可能想要这样做。例如,可能有几个创建方法具有相同的参数类型,但名称不同,例如

There are various reasons why an API designer might want to do this. For example, there might be several "creation" methods with the same parameter types, but different names, e.g.

public static Duration fromSeconds(int seconds)
public static Duration fromMinutes(int minutes)
public static Duration fromHours(int hours)

...你不能有三个重载的构造函数,但你可以给方法不同的名字。

... you couldn't have three overloaded constructors there, but you can give methods different names.