How to Create Objects for Your Android App with Java - dummies

How to Create Objects for Your Android App with Java

By Barry A. Burd

Objects can be a very useful tool in your Android app. Check out the code below which illustrates Java in action. This code contains real-life Java code to create two objects.

package com.allmycode.a09_02;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.TextView;

import com.allmycode.a09_01.BagOfCheese;

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);

BagOfCheese bag1 = new BagOfCheese();

bag1.kind = "Cheddar";

bag1.weight = 2.43;

bag1.daysAged = 30;

bag1.isDomestic = true;

BagOfCheese bag2 = new BagOfCheese();

bag2.kind = "Blue";

bag2.weight = 5.987;

bag2.daysAged = 90;

bag2.isDomestic = false;

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.

java-programming-for-android-developers-2e-running-code
Running the code.

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.

Each use of the words new 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.)

The next five statements do the same for a second variable, bag2, and a second bag of cheese.