So for the Toast class, it can apparently be written like this :
Toast toastMessage = Toast.makeText(this, "Hello", Toast.LENGTH_SHORT)
toastMessage.show();
Why exactly is it possible for toastMessage to be instantiated and used as an object without the new keyword?
How can toastMessage be instantiated by a method?
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);
}
}
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.
See more on this question at Stackoverflow