Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

4. Types and References: It’s 10:00. Do ... > Objects use variables, too

Objects use variables, too

So far, we’ve looked at objects separate from other types. But an object is just another data type. Your code treats objects exactly like it treats numbers, strings, and Booleans. It uses variables to work with them:

Using an int

  1. Write a statement to declare the integer.

    int myInt;
    
  2. Assign a value to the new variable.

    myInt = 3761;
    
  3. Use the integer in your code.

    while (i < myInt) {
    

Using an object

  1. Write a statement to declare the object.

    image with no caption
  2. Assign a value to the object.

    spot = new Dog();
    
  3. Check one of the object’s fields.

    while (spot.IsHappy) {
    
image with no caption

Objects are just one more type of variable your program can use.

If your program needs to work with a whole number that’s really big, use a long. If it needs a whole number that’s small, use a short. If it needs a yes/no value, use a boolean. And if it needs something that barks and sits, use a Dog. No matter what type of data your program needs to work with, it’ll use a variable.