package com.allmycode.a09_02;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
<strong>import com.allmycode.a09_01.BagOfCheese;</strong>
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
<strong> BagOfCheese bag1 = new BagOfCheese();</strong>
<strong> bag1.kind = "Cheddar";</strong>
<strong> bag1.weight = 2.43;</strong>
<strong> bag1.daysAged = 30;</strong>
<strong> bag1.isDomestic = true;</strong>
<strong> </strong>
<strong> BagOfCheese bag2 = new BagOfCheese();</strong>
<strong> bag2.kind = "Blue";</strong>
<strong> bag2.weight = 5.987;</strong>
<strong> bag2.daysAged = 90;</strong>
<strong> bag2.isDomestic = false;</strong>
textView.setText("");
textView.append(bag1.kind + ", " + bag1.weight + ", " +
bag1.daysAged + ", " + bag1.isDomestic + "\n");
textView.append(bag2.kind + ", " + bag2.weight + ", " +
bag2.daysAged + ", " + bag2.isDomestic + "\n");
}
}
A run of the code is shown here.
The code above creates “two BagOfCheese
objects” or “two BagOfCheese instances,” or you might say that the new BagOfCheese()
statements instantiate the BagOfCheese
class. One way or another, the code declares the existence of one class and declares another class — a class that declares the existence of two objects.
BagOfCheese()
is a constructor call.The code uses ten statements to create two bags of cheese. The first statement (BagOfCheese bag1 = new BagOfCheese())
does three things:
- With the words
BagOfCheese bag1
the first statement declares that the variable bag1
refers to a bag of cheese.
- With the words
new BagOfCheese()
the first statement creates a bag with no particular cheese in it. (If it helps, you can think of it as an empty bag reserved for eventually storing cheese.)
- Finally, with the equal sign, the first statement makes the
bag1
variable refer to the newly created bag.
The next four statements assign values to the fields of bag1
:
bag1.kind = "Cheddar";
bag1.weight = 2.43;
bag1.daysAged = 30;
bag1.isDomestic = true;
To refer to one of an object's fields, follow a reference to the object with a dot and then the field's name. (For example, follow bag1
with a dot and then the field name kind
.)
bag2
, and a second bag of cheese.