为什么Toast可以在没有new关键字的情况下实例化? [英] Why can Toast be instantiated without the new keyword?

查看:131
本文介绍了为什么Toast可以在没有new关键字的情况下实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此对于Toast类,它显然可以这样写:

So for the Toast class, it can apparently be written like this :

Toast toastMessage = Toast.makeText(this, "Hello", Toast.LENGTH_SHORT)
toastMessage.show();

为什么toastMessage可以实例化并用作没有new关键字的对象?

Why exactly is it possible for toastMessage to be instantiated and used as an object without the new keyword?

如何通过方法实例化toastMessage?

How can toastMessage be instantiated by a method?

推荐答案

没有什么特别关于 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.

这篇关于为什么Toast可以在没有new关键字的情况下实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆