Reputation: 51
So I am reading the head first android development book, and alittle confused on one of the pages.
From the code, it is showing the object array being created inside the object array class itself using (new drink()). This is abit confusing for me because I thought normally the array would be created inside a main rather than in the object itself. Can anyone help explain why?
Thank you.!
Upvotes: 0
Views: 85
Reputation: 272715
This is abit confusing for me because I thought normally the array would be created inside a main rather than in the object itself.
No. In Android development, you almost never write code in the main
method.
A Drink[]
can be created in many places. In your example, there is a static field called drinks
in the class Drink
. An array of drinks is created to assign to that field.
The drinks
field's purpose is likely to allow easy access of the different types of drinks such as Latte and Cappuccino. You don't have to create the drinks objects in the client code. You can just use Drink.drinks[0]
or Drink.drinks[1]
. In addition, the Drink
constructor is private, so the drinks
array is also your only way of accessing Drink
objects from the outside.
It might seem counter-intuitive or even paradoxical at first to have an instance of a class in that class. But note how classes are reference types. Drink
is just storing references to other Drink
objects. Not to mention that drinks
is static, so it belongs to the class itself, instead of Drink
instances.
Upvotes: 1
Reputation: 52185
As it has been stated in the comments, the constructor
of the Drink
class, is set as private, thus there is no way that you can initialize Drink
objects outside that class.
Having the creation of the drinks
array allows you a quick an easy (albeit, not traditional, if you will) access to instances of said objects.
Seeing that this is a tutorial, my guess is that eventually, the constructor will be marked as public
, and the author will introduce the concept of a service or some other mechanism which your Android app will use to get Drink
objects.
The service layer could theoretically be getting these objects from a file, service (REST, SOAP, etc.), Database, or some other data source.
Upvotes: 3