2.1. Objects - Instances of Classes

In this unit, you will learn to use objects created from classes that have been defined by other programmers. Later on, in Unit 5, you will learn to define your own classes.

2.1.1. Intro to Objects with Turtles

../_images/mindstorms_turtle.jpg

In the 1960s, an educational programming language called Logo was developed. It is best known for teaching programming with turtles! The turtles were graphical or robotic turtles that were controlled with simple commands like go forward or turn right. Here’s a photo of a robot turtle from the 1960s. The turtle had a pen attached to it. The student-programmers would steer the robot around using simple commands to create drawings with their code.

Today, we can play with virtual turtles in a graphical world. Below is a sample Java program that works with Turtle objects.

Try clicking the run button button below to see what the following program does. (If the code below does not work for you, you can also see the Turtle code in action at this repl.it link (refresh page after forking and if it gets stuck) or download the files here to use in your own IDE.)

The program above creates a World object called world and a Turtle object called yertle and places yertle in the center of the world. The code asks yertle to go forward, turn left, and then go forward. It didn’t tell the turtle how much to go forward, so it goes forward 100 pixels by default. As the turtle moves it draws with its pen. There is hidden Java code that defines the World and Turtle classes. Notice that a world was first created and then a turtle. Turtles need to be created in a world.

Note

Case matters in Java, so world and World are two different things. Also, notice that the dot operator (.) is used to run an object’s method. You can think of the (.) as asking the object to do something (execute one of its methods). For example, yertle.forward() asks the turtle yertle to go forward.

    2-1-1: Which way does a turtle face when it is first created?

  • North
  • Turtles start off facing north which is toward the top of the page.
  • South
  • Which way does yertle first move in the example above?
  • East
  • Which way does yertle first move in the example above?
  • West
  • Which way does yertle first move in the example above?

A computer doesn’t automatically know what we mean by a robot turtle or world. We have to write Java classes to define what we mean. The class defines the data that every turtle knows about itself (called fields or attributes) like where it is in the world and which way it is facing. The class also defines what objects of the class can do (called methods or behaviors) like turnRight and move forward.

You can think of a class as a classification. A class defines the type of the objects created from it and creates objects of that type. Another way to say this is that a class in Java defines a new abstract data type. When you create objects, you create a new instance (object) of that class data type. Here, yertle is an object of the class Turtle.

Also notice that the dot operator (.) is used to run an object’s method. You can think of the (.) as asking the object to do something (execute one of its methods). For example, yertle.forward() asks the turtle yertle to go forward. It doesn’t tell yertle how much to go forward, so it goes forward 100 pixels by default. The parentheses () after a method name are there in case you need to give the method arguments (some data) to do its job, for example to go forward 50 pixels instead of 100. Try changing the code above to go forward 50 pixels instead and then run it again. What happens?

        2-1-2: The following program uses a turtle to draw a sort-of sideways capital L as shown to the left,  but the lines are mixed up.  The program should do all necessary set-up: import items, start the class definition, start the main method, and create a world and turtle. Then it should ask the turtle to turn right, go forward, turn left, and then go forward 50 pixels. Next, it should ask the world to show itself.  Finally, it should close the main method and class definition. We have added a compass to the picture to indicate the directions north, south, west, and east. 

Drag the needed blocks of statements from the left column to the right column and put them in the right order. There are three extra blocks that are not needed in a correct solution. Then click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are the wrong blocks.

import java.util.*; import java.awt.*; --- public class TurtleTest { --- public static void main(String[] args) { --- World world = new World(300,300); Turtle yertle = new Turtle(world); --- yertle.turnRight(); --- yertle.right(); #paired --- yertle.forward(); --- yertle.forward() #paired --- yertle.turnLeft(); --- yertle.forward(50); --- world.show(true); --- world.show(True); #paired --- } // end main } // end class

A computer doesn’t automatically know what we mean by a robot turtle or world. We have to write Java classes to define what we mean. The class defines the data that every turtle object knows about itself (called fields or attributes) like where it is in the world and which way it is facing. The class also defines what objects of the class can do (called methods or behaviors) like turnRight and move forward.

    2-1-3: What type of thing is yertle in the program above?

  • object
  • Yes, yertle is an object of the Turtle class.
  • class
  • A class defines the data and behavior for all objects of that type.
  • attribute
  • An attribute is something the object knows about itself.
  • method
  • A method is something an object can do like go forward.

    2-1-4: What type of thing is turnRight in the program above?

  • object
  • An object has data and behavior.
  • class
  • A class defines the data and behavior for all objects of that type.
  • attribute
  • An attribute is something the object knows about itself.
  • method
  • A method is something an object can do like turn right.

    2-1-5: What type of thing is the position of a turtle in a world?

  • object
  • An object has data and behavior.
  • class
  • A class defines the data and behavior for all objects of that type.
  • attribute
  • An attribute is something the object knows about itself like its position.
  • method
  • A method is something an object can do like turn right.

Classes can inherit attributes and methods from another class in Java, just like people can inherit money from a relative. Here is a class diagram that shows some of the attributes and methods that the class Turtle inherits from the SimpleTurtle class.

Turtle class diagram

Figure 2: Turtle Class Diagram

    2-1-6: A turtle object knows how to turn by a specified number of degrees. What type of thing is turn?

  • object
  • An object has data and behavior.
  • class
  • A class defines the data and behavior for all objects of that type.
  • attribute
  • An attribute is something the object knows about itself.
  • method
  • A method is something an object can do like turn.
        2-1-7: The following program uses a turtle to draw the picture shown to the left,  but the lines are mixed up.  The program should do all necessary set-up: import items, start the class definition, start the main method, and create a world and turtle. Then it should ask the turtle to turn 45 degrees, go forward 100 pixels, turn right, and then go forward 50 pixels. Next, it should ask the world to show itself. Finally, it should close the main method and class definition. We have added a compass to the picture to indicate the directions north, south, west, and east. 

Drag the needed blocks of statements from the left column to the right column and put them in the right order. There are three extra blocks that are not needed in a correct solution. Then click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are the wrong blocks.

import java.util.*; import java.awt.*; --- public class TurtleTest { --- public static void main(String[] args) { --- World world = new World(300,300); Turtle yertle = new Turtle(world); --- yertle.turn(45); --- yertle.turnRight(45); #paired --- yertle.forward(100); --- yertle.turnRight(); --- yertle.forward(50); --- yertle.forward(50; #paired --- world.show(true); --- world.show(true) #paired --- } // end main } // end class

coding exercise Coding Exercise

In the code below, yertle goes forward and then turns left. Can you change the code to make yertle go forward twice and then turnRight?

When you write a class like the Turtle class, you can create many objects of that class type. In the code below, two turtle objects are created: yertle and myrtle. You can name your turtle and add in a line like the following in the main method to make it move:

// To create or declare a new object, write:
// ClassName variableName = new ClassName(arguments);
Turtle yourTurtleName = new Turtle(world);
yourTurtlename.forward();

coding exercise Coding Exercise:

Can you add another turtle object to the code below?

2.1.2. What are Classes and Objects?

In Java, a class is used to define a new abstract data type (classify something). The class defines what objects of the class need to know (attributes or instance variables) and do (behaviors or methods). A class is the formal implementation, or blueprint, of the attributes and behaviors of an object.

There are many classes that are part of the Java language, but you only have to know a few of these for the AP CS A exam (String, Math, System, ArrayList).

The real power of Java is the ability to create your own classes (define your own types). You will learn how to create your own classes in Unit 5.

Here’s a Greenfoot video, which was created using the free software Greenfoot (http://greenfoot.org), where you can see ant objects doing actions like moving and eating. Greenfoot makes it easy to create 2d simulations and games in Java. See http://www.greenfoot.org/doc/tut-2 for a tutorial if you are interested in learning more about Greenfoot.

You can think of a class like a cookie cutter. It is used to create the cookies (objects) and can be used to create as many cookies (objects) as you want. A class can also be thought of as a factory that produces objects.

../_images/cookieCutter.png

Figure 3: Using a cookie cutter to make cookies

You can think of a class as the type or classification. The following picture has lots of cats (objects of the type cat). They are all different, but they share the same attributes and behaviors that make up a cat.

../_images/cats2.png

Figure 4: Pictures of cats (cat objects)

If you go to a restaurant, you will be seated by the greeter, the waiter will take your order, and the chef will cook your food. What do we mean by a greeter, waiter, and chef? Those are classifications or types of workers in a restaurant. Java has this same concept. When we create a new class we are defining a new type (a new classification) to the computer. Each type can have abilities or behaviors (called methods in Java) and attributes (called instance variables in Java). After you define a type, you can use it to create objects of that type. All objects created from a class will have the properties and abilities/behaviors defined in that class. For example, all turtle objects will know how to move forward and turn.

exercise Check your understanding

    2-1-8: How many objects can you create from a class in Java?

  • 1
  • There is one definition of a class, but the class can create as many objects as are needed.
  • 10
  • There is no limit on the number of objects you can create from a class.
  • 1000
  • There is no limit on the number of objects you can create from a class.
  • As many as you need
  • You can create as many objects as you need from one class.

    2-1-9: What specifies the behavior for objects of a class in Java?

  • attributes
  • attributes specify the data that an object keeps track of.
  • methods
  • Methods specify the behavior of all objects of a class.
  • class
  • While the class does specify the behavior of all objects created by that class, what part of a class specifies the behavior?
  • object
  • The object behavior is specified by the methods in the class that created the object.

    2-1-10: What specifies the data or state for an object in Java?

  • attributes
  • attributes specify the data that an object keeps track of.
  • methods
  • Methods specify the behavior of all objects of a class.
  • class
  • While the class does specify the data or state that all objects of the class keep track of, what part of the class stores the data?
  • object
  • The object data or state is stored in the attributes of the object. The attributes are defined in the class.

2-1-11: What are some attributes of cats? What are some behaviors of cats? (Note that attributes are nouns or adjectives describing features of cats, and behaviors are verbs).

2.1.3. groupwork Programming Challenge : Turtle Drawing

We encourage you to work in pairs for this challenge.

Create a Turtle object below and have it draw a shape. For example, have it draw a small square and then a large square by calling the forward method multiple times. In the next lessons, we will draw more complicated shapes. Here are some simple turtle methods that you could use:

  • forward();

  • turnLeft();

  • turnRight();

  • backward();

  • penUp();

  • penDown();

After writing your code below, if you’d like your own copy, you can open this repl.it link, copy in your code, and save it in your own repl.it account.

2.1.4. Summary

  • A class defines a new data type (a classification). It is the formal implementation, or blueprint, of the attributes and behaviors of the objects of that class.

  • An object is a specific instance of a class with defined attributes. Objects are declared as variables of a class type.

  • An attribute is data the object knows about itself. For example a turtle object knows the direction it is facing.

  • A method is something that an object can do. For example a turtle object can go forward 100 pixels.

  • An abstract data type is a definition of the attributes and methods for all objects of a type (of the same class).

  • An instance variable is another name for an attribute, which is data an object knows about itself such as its position.

2.1.5. AP Practice

    2-1-12: A student has created a Dog class. The class contains variables to represent the following.
    • A String variable called breed to represent the breed of the dog

    • An int variable called age to represent the age of the dog

    • A String variable called name to represent the name of the dog

    The object pet is declared as type Dog. Which of the following descriptions is accurate?

  • An attribute of the name object is String.
  • name is an attribute of the pet object or Dog class.
  • An attribute of the pet object is name.
  • name is an attribute of the pet object or Dog class.
  • An instance of the pet class is Dog.
  • An instance of the Dog class is pet.
  • An attribute of the Dog instance is pet.
  • An attribute of the Dog class is name.
  • An instance of the Dog object is pet.
  • An instance of the Dog class is pet.
    2-1-13: A student has created a Party class. The class contains variables to represent the following.
    • An int variable called numOfPeople to represent the number of people at the party.

    • A boolean variable called discoLightsOn to represent whether the disco ball is on.

    • A boolean variable called partyStarted to represent whether the party has started.

    The object myParty is declared as type Party. Which of the following descriptions is accurate?

  • An attribute of the myParty object is boolean.
  • An attribute of myParty is numOfPeople.
  • An attribute of the Party class is myParty.
  • myParty is an instance of the Party class.
  • An instance of the Party class is myParty.
  • myParty is an object that is an instance of the Party class.
  • An attribute of the Party instance is myParty.
  • An attribute of the Party class is numOfPeople.
  • An instance of the Party object is numOfPeople.
  • An attribute of the Party class is numOfPeople.
You have attempted of activities on this page
Next Section - 2.2. Creating and Initializing Objects: Constructors