Chapter 1
Objects and Classes  

powered by FreeFind

Modified: 

Overview

The basic concepts and terms of solving problems using a computer are covered, including use of the BlueJ application and object oriented modeling of problems.

1.1 Objects and Classes

Problems solved on computers model some aspect of the real world.

For example, we calculate the date when the distance between Earth and Mars is a minimum (August 27, 2003) by modeling the planetary orbits numerically. The line between reality and computer modeling apparently grows less distinct when money is earned and spent electronically or the plane we ride is often piloted by a computer, but even in these cases the computer programmer has implemented a model solution for the computer to follow.

Model solutions can be expressed as picture, a recipe, explanations, mathematically, etc.; a program expresses the model in a computer language. When the model followed by the computer corresponds to the real world, the computer produces correct results. Your challenge in this course is to design a valid model and implement the model faithfully in a computer language named Java.

Object-oriented programming is one approach to modeling problems based upon how we humans naturally organize our environment - by classifying things with similar attributes together. For example, on entering a room we unconsciously classify individual objects in the room as desks, students, etc. We can then treat desks as setting objects without thinking much about the details of an individual desk.

A room may have 20 objects classified as desks, each desk has color, height, location, etc. fields. Two desk objects, Desk 1 and Desk 2, are different instances of the same desk class, have common fields but different field values as in the example:

Desk 1
height   30 inches
color      black
location row 3, position 2
        Desk 2
height   30 inches
color      tan
location row 4, position 1

 

Exercise 1
  1. Name two classes of objects in your immediate possession at this moment. Nothing risqué please!
  2. Write each of the two class names and three obvious fields for each class.
  3. Pick one class for which you possess several objects and define values for each of the three fields.

 

1.2 Creating Objects

Create object - To create a new instance of a real desk requires lumber, nails, etc. but since we are modeling a desk on a computer two new desk instances are created in Java by:

new Desk()
                                 
new Desk()

 

Name object - Naming each desk allows us to distinguish one desk from another in Java by:

Desk desk1 = new Desk()
            
Desk desk2 = new Desk()

 

Now we can refer to either of the two desk objects by their name, desk1 or desk2.

desk1
height   30 inches
color      black
location row 3, position 2
            desk2
height   30 inches
color      tan
location row 4, position 1

 

Exercise 2   From Exercise 1, Question 3
  • Give the Java to create and name two of the objects.

 

BlueJ

The following assumes that textbook projects has been installed, if not, see Getting Started.

You should now see the following indicating that shapes project has been opened:

 

Exercise 3 - Creating objects in BlueJ
  1. Right-click on the Circle class icon and choose:
    • new Circle()
  2. Create another circle.
  3. Create a square.

The three new objects should appear as below.

1.3 Calling Methods

Exercise 3 created two circles that included an isVisible field that when false the circle is not visible and when true the circle is visible.

circle1                    circle2
diameter    30
isVisible     false
 
diameter    30
isVisible     false

 

Method makeVisible() sets the isVisible field to true.

 

Exercise 4 - Calling methods in BlueJ
  1. Right-click on circle1 icon . Choose makeVisible().
  2. Right-click on the taskbar icon .
  3. Right-click on circle1 icon. Choose moveUp(). Repeat several times.
  4. Make circle1 invisible and visible several times.

 

1.4 Parameters

Two circles have been created with field values of:

circle1                    circle2
diameter    30
isVisible     false
 
diameter    30
isVisible     false

The method call changeSize(50) specifies 50 as the parameter to the method.

Exercise 5 - Calling methods with parameters in BlueJ                                                                 
  1. Right-click on circle1 icon in BlueJ.
  2. Choose makeVisible().
  3. Click on the taskbar icon .
  4. Right-click on circle1 icon in BlueJ.
  5. Choose changeSize(int).
  6. Make circle1 diameter 150 as at right.
  7. Figure out how to call slowMoveVertical method.

 

1.5 Data types

Describing real problems as a computer model requires defining the problem's data.

The following fields describe the Circle instance named circle1's diameter, visibility, and color.

circle1  
int          diameter   30
boolean isVisible     false
String    color           "blue"
 

 

Exercise 6 - Calling methods with String parameters                                                               
  1. Click on the taskbar icon .
  2. Right-click on circle1 icon in BlueJ .
  3. Call changeColor method with parameter "red".
  4. Call changeColor method with parameter "Mary".
  5. Call changeColor method with parameter red.
  6. Call changeColor method with parameter 14.
  7. Call changeColor method with parameter 'red'.

1.6 Multiple Instances

  circle1        circle2
Two objects (i.e. instances) of the Circle class     
diameter    30
isVisible     false
 
diameter    30
isVisible     false
Exercise 7 - Multiple Instances                                                               
  1. Create three Circle objects by right-clicking on .
    • Make each visible.
    • Move each around.
    • Make each a different color.
  2. Create two Triangle objects.
    • Make each visible.
    • Move each around.
    • Make each a different color.

1.7 State

The following field values completely define circle1's state. If the state (any field value) does not change, the object does not change. Changing field diameter to 90 changes the state of the object (and triples the diameter).

circle1  
int          diameter   30
int          xPosition   70
int          yPosition   60
boolean isVisible     false
String    color           "blue"
 

 

Exercise 8 - Inspecting Object State                                                               
  1. Click on the taskbar icon .
  2. Inspect the state of circle1 by right-clicking on .
    • Choose Inspect.
    • Call changeColor method using a different color parameter.
    • Note the color field value.
  3. Inspect two objects of the same class (you should have two Circle objects, if not create another).
    1. Are all fields the same name?
    2. Are all values the same?
  4. Inspect a Triangle and Circle object simultaneously (create if necessary).
    • What fields are the same?
    • What fields are different?

 

1.8 What is an object?

All objects of a class have identical fields; the fields of one object can hold different values from other objects.

Circle class     circle1 object      circle2 object
int          diameter      
int          xPosition
int          yPosition

boolean isVisible
String    color    
 
int          diameter   30
int          xPosition   70
int          yPosition   60
boolean isVisible     false
String    color           "blue"   
 
int          diameter   30
int          xPosition   140
int          yPosition   72
boolean isVisible     true
String    color           "red"   

All objects of a class have identical methods; methods are called on a single designated object.

Circle methods  
void changeColor(String)
void changeSize(int)
void makeInvisible()
void makeVisible()
void modeDown()
 

 

Exercise 9 - Using Objects      
  1. Create a house and sun similar to the picture at right using the shapes project classes Circle, Triangle and Square.
     
  2. Write down what tasks you did; list the objects created and methods called. For example:

     

    1. Circle circle1 = new Circle()
    2. circle1 makeVisible()
    3.       :

     

  3. Could the methods be called in any other order?

1.9 Object Interaction

The tasks of Exercise 9 would normally be written in a file as Java instructions that could be performed by the computer rather than entering by hand each time a house is to be drawn. In Exercise 10, the tasks have been written to the picture project which the computer uses to perform the tasks.

Exercise 10 - Object Interaction      
  1. Open the picture project.
    1. Click Project | Open Project
    2. Type File Name:
      • J:\C201\Projects\chapter01
    3. Click on:
      • chapter01 | picture
  2. Create an instance of class Picture.
  3. Call the draw method using picture1 object.
  4. Open the icon to see the results.

1.10 Source Code

Tasks to create objects and call methods can be written in Java, saved to a file, and reused over and over. The list of Java statements define a new class, the written text of the statements are the source code for the class.

Exercise 11 - Source Code     
  1. Open the picture project.
  2. Right-click on icon .
  3. Right-click on Open Editor to see the source code text.
  4. What is the name of the class?
    • Find the source code statement that defines the name of the class.
  5. Find the fields for the sun and parts of the house.
    • What are the field names?
  6. Find the public void draw method.
    • What are the wall tasks?
    • Does the order in which the tasks are performed matter?

Java statements are written and read by humans but must be compiled (translated from Java to computer code) before performed by computer.

 

Exercise 12 - Compiling     
  1. Right-click on icon .
  2. Open Editor to see the source code text.
  3. Find the public void draw() method.                                           
    • Change the color of the sun to blue.
    • Compile the Picture instructions by clicking the Compile button (see figure at right).
    • What happened to picture1 object?
    • Was picture1 object using the most recent definition of Picture class?
  4. Create an instance of class Picture named picture1.
    • Call the draw method.
    • Open the icon to see the results.

 

Exercise 13 - Editing     
  1. Open Editor to see the source code text.
  2. Change the Picture class to have two suns.
    1. Add another Sun field named sun2.
    2. Compile by right-clicking Compile button.
    3. Create an instance of class Picture named picture1.
    4. Call the draw method.
  3. Did two sun's appear? What happened?
  4. Change the draw method appropriately for sun2.
    1. Copy and paste sun source code.
      1. Make necessary changes of sun to sun2.
      2. Make sun2 a color different than sun.
      3. Position sun2 below sun.
    2. Compile by right-clicking Compile button.
    3. Create an instance of class Picture named picture1.
      • Call the draw method.
  5. Did two sun's appear? What happened?

 

Exercise 14 - Challenge
  1. Open Editor to see the source code text.
  2. Change the draw method to add a sunset of a sun.
    • Use the slowMoveVertical(int) method.
  3. Compile by right-clicking Compile button.
  4. Create an instance of class Picture named picture1.
    • Call the draw method.
    • Open the icon to see the results.
    • Call the draw method again to see the sunset.

 

Exercise 15 - Challenge     
  1. Open Editor to see the source code text.
  2. Add a new method named sunset.
    • Use public void draw() as a pattern.
    • Move the slowMoveVertical call to the sunset method.
  3. Compile by right-clicking Compile button.
  4. Create an instance of class Picture named picture1.
    • Call the draw method.
    • Open the icon to see the results.
    • Call the sunset method to see the sunset.

1.11 Another Example

This is a simple example of a student database that tracks students in a laboratory class and prints class lists.

Exercise 16 - Student Database 

In BlueJ    

  1. Open project lab-classes.
  2. Create a Student object.
    • Fill in the fullName parameter with "Lisa Simpson"
    • and studentID parameter with "122044".
  3. Inspect the object.
    • How many fields does a Student object have?

1.12 Return Values

Calling a method can produce a return value as a result. When the name field is "Lisa Simpson", the Student class method getName produces the return value "Lisa Simpson".

        

Exercise 16.5 - Signatures     
  1. What is the method name of:
    1. public String getName()
    2. public void changeName(String replacementName)
    3. public String getStudentID()
       
  2. What is the parameter class and parameter name of:
    1. public String getName()
    2. public void changeName(String replacementName)
    3. public String getStudentID()
    4. public void addCredits( int additionalPoints )
       
  3. What is the return value class of:
    1. public String getName()
    2. public void changeName(String replacementName)
    3. public String getStudentID()
    4. public int getCredits()
    5. public String getLoginName()
    6. public void print()
Exercise 17 - Return Values of Methods      

In BlueJ

  1. Continue Exercise 16.5.
  2. Create a second Student object.
    • Fill in the fullName parameter with "Charlie Brown"
    • and studentID parameter with "123456".
  3. Inspect each Student object but don't close inspector.
  4. Call method getStudentID for each object.
  5. Find the signature of the getStudentID method.
    • Right-click on the Student class.
    • Click Open Editor.
    • What are the getStudentID method parameter name and class?
    • What class is the return value?
    • What field is returned?
    • Call method getStudentID for one of the Student objects.
      • What value is returned?
  6. Find the signature of the changeName method.
    • Right-click on a Student object.
    • What are the changeName method parameter name and class?
    • What class is the return value?
    • Call method changeName for one of the Student objects.
      • What value is returned?
    • Call method getName for the Student object.
      • What value is returned?

 

1.13 Objects as Parameters - LabClass

Any object can be a method parameter, as long as the object class matches the method signature.

Exercise 18 - LabClass
  1. Continue Exercise 17.
  2. Create a LabClass object with maximum of 5 students
    • The LabClass constructor signature indicates an int parameter which must be passed the maximum number of students.
  3. Call the numberOfStudents LabClass method.
    • What is the result?

The enrolStudent method is passed a Student parameter.

Exercise 19 - Objects as Parameters
  1. Continue Exercise 18.
  2. You should have two Student objects, each with different name and id fields.
  3. Call enrolStudent method on the LabClass object with the name of one Student object as the parameter (e.g. student2).
    • The enrolStudent signature indicates a parameter of class Student must be passed.

       

  4. Call the numberOfStudents LabClass method.
    • What is the result?
  5. Call LabClass method enrolStudent with the same Student object as before.
  6. Call the numberOfStudents method again.
    • What is the result?
    • What does the numberOfStudents method do?

The printList method prints the fields of a LabClass object to a terminal window.

Exercise 20 - Print LabClass object
  1. Continue Exercise 19.
     
  2. Call the printList method for the LabClass object.
    • What does the printList method do?
       
  3. Call the printList method again.

Practice for Homework 2

Exercise 21 - Exploring LabClass
  1. Continue Exercise 20.
     
  2. In BlueJ menu:
    • Click View
    • Check Show Terminal.
       
  3. In Terminal Window:
    • Click Options
    • Check Record method calls.
       
  4. For the two Student objects, figure out and use the methods needed to change the name and credits to the following field values:
    1. Ms. Lisa Simpson, student ID: 122044, credits: 56
    2. Mr. Charlie Brown, student ID: 123456 credits: 6
    • Open the Terminal Window. What happened?

     

  5. Call LabClass method enrolStudent to enter the two Student objects.
    • Call the printList method for the LabClass object.

 

 

 

 

 

Exercise 22 - Exploring LabClass
  1. Continue Exercise 21.
  2. Figure out and use methods to set the instructor, room, and lab time fields of the LabClass object.
  3. Call the printList method for the LabClass object.
  4. Inspect the LabClass object.

 

Exercise 23 - Printing Terminal Window

The Terminal Window should include the results of Exercises 21 and 22. To print:

  1. Open the Terminal Window.
  2. Drag the mouse over the results (hold the mouse left button down and move the mouse).
  3. Click Options | Copy
  4. Paste into Word.