Activity 1 - Classes and Objects

Classes and Objects

Classes and objects are the two main aspects of object oriented programming. A class defines a new data type, whereas an object is an instance of a particular class. Objects store their data in fields defined by the object’s class. Objects also have functionality that can be activated by calling the methods that belong to its class.

A UML diagram is a graphical summary of the data and methods in a class. Below is the UML diagram for the Rectangle class from the Simple Java Graphics library written by Cay S. Horstmann.

Critical Thinking Questions

  1. Identify one example of a data field for the Rectangle class from the above UML diagram.

    1. What is the variable name of the data field?
    2. What is the data type of the data field?
  2. Identify one example of a Rectangle class method that takes no arguments.

    1. What is the method name?
    2. How do you know that the method does not take any arguments?
    3. Does the method return a value? If so, what type of value will it return?
    4. Do you think this method will modify one or more of the object’s data fields? Why or why not?
  3. Identify one example of a Rectangle class method that takes one or more parameters.

    1. What is the method name?
    2. What is the name and data type of each parameter for the method?
    3. Does the method return a value? How do you know?
    4. Do you think this method will modify one or more of the the object’s data fields? Why or why not?
  4. Imagine that you have a code segment that creates a rectangle (rect1) with the following values for each of its fields:

    Give the code to do each of the following to rect1

    1. Change the color of rect1 to color Violet.
    2. Fill rect1.
    3. Grow the width of rect1 by 100 units and the height by 200 units.
    4. Get the width and height of rect1.

    What values do you think will be returned by part d?

  5. There is something unusual about those get... methods compared to the fields they correspond to, what is that?

Terminology Note

A method should do one thing, either provide access to object data values or mutate data values. Never both (with some exceptions)!