Overview

In this reading we’ll continue our journey into writing our own classes. We’ll look at a common idiom used in Java where fields are protected by accessor and modifier methods.

Required Reading

Sections 11.4 - 11.5 (pp. 356-366) from the course textbook.

Learning Objectives

BASIC Learning Objectives

Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.

  1. Write Java code that initializes an array of values and prints out all values in an array using a loop.
  2. Compare and contrast the “Step Over,” “Step Into,” and “Step Out” actions in the DrJava debugger.
  3. Given an object, write a line of Java code that prints out the contents of a public field in that object.
  4. Compare and contrast the method headers of accessors (getters) and modifiers (setters).
  5. Define encapsulation.

ADVANCED Learning Objectives

The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.

  1. Read, write, and trace code that involves an array of any arbitrary type of value (e.g. int or double).
  2. Write classes that use getters and setters.
  3. Identify the commonalities between all getters and setters.

Pre-class Exercises

These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.

  1. Consider the following array of integers.

    15 8 34 19 -3 15 -522

    Part A: Write a single line of Java code to create this array. You may call the array whatever you want.

    Part B: Write Java code that uses a “For-Each” loop to print out all values in the array.

    Part C: Repeat Part B but use a regular for loop.

  2. Consider the following class.

    public class Foo {
        public int x;
        private int y;
    
        public Foo(int a, int b) {
            this.x = a;
            this.y = b;
        }
    
        public int getY() { return this.y; }
        public void setY(int i) { this.y = i; }
    }

    Assume that you create a Foo object as follows.

    Foo f = new Foo(1, 5);

    Part A: Write a line of Java code to print out the contents of the x field in f.

    Part B: Repeat part A but assume that you want to print out the y field in f.