9.6. Additional Practice Exercises

9.6.1. Code Tracing

Part 1

Use the UML diagram below to answer the questions in this section:

  1. Implement a copy constructor for Device. (Note: Copy id and status from another Device.)

    Solution
    // inside Device.java
    public Device(Device other) {
        this.id = other.id;       // private but accessed within same class
        this.status = other.status;
    } // Device
    
  2. Implement toggleStatus() to flip status between true and false.

    Solution
    // inside Device.java
    public void toggleStatus() {
        status = !status;   // flips true <-> false
    } // toggleStatus
    
  3. Answer the questions below about the following code:

     1package cs1302.driver;
     2
     3import cs1302.devices.Device;
     4
     5/**
     6 * Demonstrates usage of the {@code Device} class.
     7 */
     8public class DeviceDriver {
     9
    10    /**
    11     * The entry point of the program.
    12     *
    13     * @param args command-line arguments
    14     */
    15    public static void main(String[] args) {
    16        Device d1 = new Device("Router1");
    17
    18        // 1. Try direct access to status
    19        d1.status = true; // LINE 1
    20
    21        // 2. Call toggleStatus
    22        d1.toggleStatus(); // LINE 2
    23        System.out.println(d1);
    24
    25        // 3. Create new Device using copy constructor
    26        Device d2 = new Device(d1); // LINE 3
    27        System.out.println(d2);
    28    } // main
    29} // DeviceDriver
    
    1. Will LINE 1 compile?

      Solution

      LINE1 fails — status is private, so external code (outside Device) cannot touch it directly.

    2. Will LINE 2 compile?

      Solution

      LINE2 compiles. toggleStatus() is public and exposes a safe way to change the internal state

    3. Can DeviceDriver create a copy using LINE 3?

      Solution

      LINE3 compiles. The copy constructor is public, so DeviceDriver can use it.

Part 2

Use the UML diagram below to answer the questions in this section:

  1. Answer the questions below about the following code:

    Listing 9.14 in DeviceDriver.java
     1package cs1302.driver;
     2
     3import cs1302.devices.Device;
     4import cs1302.devices.DeviceManager; // <-- LINE 1
     5
     6/**
     7 * Demonstrates usage of the {@code Device} and {@code DeviceManager} classes.
     8 */
     9public class DeviceDriver {
    10
    11   /**
    12    * The entry point of the program.
    13    *
    14    * @param args command-line arguments
    15    */
    16    public static void main(String[] args) {
    17       Device d1 = new Device("Router1");
    18
    19       // Use DeviceManager here:
    20       DeviceManager dm = new DeviceManager(); // <-- LINE 2
    21       dm.resetDevice(d1); // <-- LINE 3
    22    } // main
    23} // DeviceDriver
    
    1. Can we import DeviceManager in DeviceDriver (LINE 1)?

      Solution

      No. DeviceManager is package-private, so it is not visible outside cs1302.devices. The compiler will give the following error:

      error: DeviceManager is not public in cs1302.devices;
      cannot be accessed from outside package
      
    2. Can we create a DeviceManager object in DeviceDriver (LINE 2)?

      Solution

      No. Since the class itself is not visible, its constructor isn't visible either. The compiler won't even recognize DeviceManager.

    3. Can we call resetDevice(d1) on a DeviceManager object from DeviceDriver (LINE 3)?

      Solution

      No, for the same reason. Even though resetDevice is public, it belongs to a package-private class. The class itself must first be visible, which it is not.

    4. Where can DeviceManager be used?

      Solution

      Only in the same package cs1302.devices. For example, if we had TestDeviceManager.java inside cs1302.devices, it could use DeviceManager without issues.

Part 3

Consider the UML below where we add another class SmartLight that extends Device and uses protected members.

  1. Implement the SmartLight constructor to call the protected Device constructor.

    Solution
    Listing 9.15 in SmartLight.java
    1public SmartLight(String id, String firmware) {
    2    super(id, firmware);
    3    this.brightness = 0;
    4    this.isOn = false;
    5
    6    this.firmwareVersion = firmware; // optional: setting inherited field
    7} // SmartLight
    
  2. Can SmartLight access the protected firmwareVersion?

    Solution

    Yes. Subclasses have access to protected members of their parent class.

    this.firmwareVersion = firmware;
    
  3. In SmartLightDriver, can we call light.updateFirmware("1.1.0")?

    Solution

    No. Protected members are not visible to classes in a different package unless they are subclasses. SmartLightDriver is neither in the same package nor a subclass.

  4. Can SmartLightDriver call light.turnOn()?

    Solution

    Yes. turnOn() is public, so accessible anywhere.

  5. Why can SmartLight access updateFirmware() but SmartLightDriver cannot?

    Solution

    Protected members are accessible to subclasses. SmartLight is a subclass of Device, so it can use updateFirmware(). SmartLightDriver is not a subclass and is in a different package, so it cannot access protected members.

9.6.2. Parsons Problems

Review these sections as needed:

Each problem specifies the caller's class and package and the relevant visibilities. Preserve those declarations unless the prompt explicitly asks you to choose one. Use every correct block once and leave incorrect blocks unused. Arrange blocks vertically and set their indentation; each level represents four spaces. Keep indentation within a block unchanged.

The text version supports solving on paper or without JavaScript. Letters identify whole blocks. Attempt each problem before opening its sample solution. A solution must satisfy the stated visibility requirements as well as compile and produce the required behavior.

The problems use two versions of Book:

  • Problems 1–3 use the simplified Book whose superclass is Object.

  • Problems 4–8 use Book extends Product.

Each problem repeats the context needed to solve it independently. The UML diagrams show only the declarations relevant to each problem; + denotes public visibility and ~ denotes package private visibility for the top-level classes shown.

Problem 1: Declare Private State and a Public API

Use the simplified Book class shown below. Its superclass is Object. The diagram specifies the required visibilities.

Source file: cs1302/books/Book.java

Assemble Book.java with the specified visibilities. Code in another package must be able to construct a book and call getTitle(), but must not access title directly. Keep each supplied declaration intact. The instance variable, constructor, and methods may appear in any order inside the class; the grader accepts those orders.

Unused Blocks
Solution Construction

Text version of Visibility Problem 1

Use the simplified Book class shown below. Its superclass is Object. The diagram specifies the required visibilities.

Source file: cs1302/books/Book.java

Assemble Book.java with the specified visibilities. Code in another package must be able to construct a book and call getTitle(), but must not access title directly. Keep each supplied declaration intact. The instance variable, constructor, and methods may appear in any order inside the class; the grader accepts those orders.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

package cs1302.books;

/** A book used to demonstrate private access and reference values. */
public class Book {

Block B

/**
 * Replace the stored title reference value.
 * @param title the new title reference value
 */
private void setTitle(String title) {
    this.title = title;
} // setTitle

Block C

} // Book

Block D

/** Reference to this book's title string. */
private String title;

Block E

/**
 * Obtain the stored title reference value.
 * @return the title reference value
 */
public String getTitle() {
    return this.title; // return with the title reference value
} // getTitle

Block F

/** Reference to this book's title string. */
public String title;

Block G

/**
 * Initialize a book with the supplied title reference value.
 * @param title reference to the title string
 */
public Book(String title) {
    super();
    this.setTitle(title);
} // Book

Block H

package cs1302.books;

/** A book used to demonstrate private access and reference values. */
class Book {
Text version of Visibility Problem 1

Use the simplified Book class shown below. Its superclass is Object. The diagram specifies the required visibilities.

Source file: cs1302/books/Book.java

Assemble Book.java with the specified visibilities. Code in another package must be able to construct a book and call getTitle(), but must not access title directly. Keep each supplied declaration intact. The instance variable, constructor, and methods may appear in any order inside the class; the grader accepts those orders.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

package cs1302.books;

/** A book used to demonstrate private access and reference values. */
public class Book {

Block B

/**
 * Replace the stored title reference value.
 * @param title the new title reference value
 */
private void setTitle(String title) {
    this.title = title;
} // setTitle

Block C

} // Book

Block D

/** Reference to this book's title string. */
private String title;

Block E

/**
 * Obtain the stored title reference value.
 * @return the title reference value
 */
public String getTitle() {
    return this.title; // return with the title reference value
} // getTitle

Block F

/** Reference to this book's title string. */
public String title;

Block G

/**
 * Initialize a book with the supplied title reference value.
 * @param title reference to the title string
 */
public Book(String title) {
    super();
    this.setTitle(title);
} // Book

Block H

package cs1302.books;

/** A book used to demonstrate private access and reference values. */
class Book {
Sample solution for Visibility Problem 1

Block order: A, D, G, E, B, C.

Indentation levels: 0, 1, 1, 1, 1, 0.

package cs1302.books;

/** A book used to demonstrate private access and reference values. */
public class Book {
    /** Reference to this book's title string. */
    private String title;
    /**
     * Initialize a book with the supplied title reference value.
     * @param title reference to the title string
     */
    public Book(String title) {
        super();
        this.setTitle(title);
    } // Book
    /**
     * Obtain the stored title reference value.
     * @return the title reference value
     */
    public String getTitle() {
        return this.title; // return with the title reference value
    } // getTitle
    /**
     * Replace the stored title reference value.
     * @param title the new title reference value
     */
    private void setTitle(String title) {
        this.title = title;
    } // setTitle
} // Book

The public top-level class and public constructor and accessor allow callers in another package to create a book and read its title reference value. The package private class alternative prevents that use from another package. The public instance variable alternative compiles, but violates the required private visibility: it would allow callers to change title directly. The private setTitle method is accessible from the constructor because both declarations occur in Book. The getter returns with the reference value stored in title, not with a copy of the String object.

Problem 2: Copy a Title Inside Book

Work inside the simplified Book class shown below. Its superclass is Object. This exercise adds the copy constructor shown in the diagram.

The argument supplied for other is a reference to a book whose title is "LOTR".

Source file: cs1302/books/Book.java

Assemble the copy constructor. Explicitly call super(), then copy the reference value stored in the other book's title instance variable into this book's title instance variable. Do not create a new String object or modify the other book.

Unused Blocks
Solution Construction

Text version of Visibility Problem 2

Work inside the simplified Book class shown below. Its superclass is Object. This exercise adds the copy constructor shown in the diagram.

The argument supplied for other is a reference to a book whose title is "LOTR".

Source file: cs1302/books/Book.java

Assemble the copy constructor. Explicitly call super(), then copy the reference value stored in the other book's title instance variable into this book's title instance variable. Do not create a new String object or modify the other book.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

} // Book

Block B

/**
 * Copy another book's title reference value.
 * @param other non-null reference to a book object
 */
public Book(Book other) {

Block C

super();

Block D

this.title = other.title;

Block E

this.title = this.title;
Text version of Visibility Problem 2

Work inside the simplified Book class shown below. Its superclass is Object. This exercise adds the copy constructor shown in the diagram.

The argument supplied for other is a reference to a book whose title is "LOTR".

Source file: cs1302/books/Book.java

Assemble the copy constructor. Explicitly call super(), then copy the reference value stored in the other book's title instance variable into this book's title instance variable. Do not create a new String object or modify the other book.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

} // Book

Block B

/**
 * Copy another book's title reference value.
 * @param other non-null reference to a book object
 */
public Book(Book other) {

Block C

super();

Block D

this.title = other.title;

Block E

this.title = this.title;
Sample solution for Visibility Problem 2

Block order: B, C, D, A.

Indentation levels: 0, 1, 1, 0.

/**
 * Copy another book's title reference value.
 * @param other non-null reference to a book object
 */
public Book(Book other) {
    super();
    this.title = other.title;
} // Book

Private access is determined by where the access occurs, not by which object is involved. Both this.title and other.title are accessible inside Book. The assignment copies a reference value: the two distinct book objects then refer to the same title string through their instance variables. The alternative assignment only copies the new book's initial null value back into its own title variable; it compiles but fails to copy the other book's title.

Problem 3: Read a Title from BookDriver

Place this main method in BookDriver. The simplified Book shown here has Object as its superclass.

Source file: cs1302/books/BookDriver.java

Create a book with title "LOTR", read its title reference value into title, then print that value. Preserve Book's existing visibilities.

Unused Blocks
Solution Construction

Text version of Visibility Problem 3

Place this main method in BookDriver. The simplified Book shown here has Object as its superclass.

Source file: cs1302/books/BookDriver.java

Create a book with title "LOTR", read its title reference value into title, then print that value. Preserve Book's existing visibilities.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

} // main

Block B

String title = book.getTitle();

Block C

Book book = new Book("LOTR");

Block D

System.out.println(title);

Block E

String title = book.title;

Block F

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {
Text version of Visibility Problem 3

Place this main method in BookDriver. The simplified Book shown here has Object as its superclass.

Source file: cs1302/books/BookDriver.java

Create a book with title "LOTR", read its title reference value into title, then print that value. Preserve Book's existing visibilities.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

} // main

Block B

String title = book.getTitle();

Block C

Book book = new Book("LOTR");

Block D

System.out.println(title);

Block E

String title = book.title;

Block F

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {
Sample solution for Visibility Problem 3

Block order: F, C, B, D, A.

Indentation levels: 0, 1, 1, 1, 0.

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {
    Book book = new Book("LOTR");
    String title = book.getTitle();
    System.out.println(title);
} // main

BookDriver can call the public getTitle() method on the accessible public Book class. That method returns with the title reference value; title stores that value, and the output is LOTR. Being in the same package does not permit BookDriver to access Book's private instance variable. The direct-access alternative produces a compile-time error.

Problem 4: Call a Package Private Method

Place this main method in InventoryDriver, with import cs1302.books.Book; already present.

addItem checks its argument and sets the supplied product's serial number to 15. nullCheck only rejects a null argument value.

Source file: cs1302/inventory/InventoryDriver.java

Obtain a manager and create a book, then call addItem to set that book's serial number. Print the resulting serial number, 15. Keep all existing visibilities unchanged.

Unused Blocks
Solution Construction

Text version of Visibility Problem 4

Place this main method in InventoryDriver, with import cs1302.books.Book; already present.

addItem checks its argument and sets the supplied product's serial number to 15. nullCheck only rejects a null argument value.

Source file: cs1302/inventory/InventoryDriver.java

Obtain a manager and create a book, then call addItem to set that book's serial number. Print the resulting serial number, 15. Keep all existing visibilities unchanged.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

InventoryManager manager = InventoryManager.getManager();
Book book = new Book("LOTR");

Block B

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {

Block C

manager.addItem(book);

Block D

System.out.println(book.getSerial());

Block E

} // main

Block F

InventoryManager.nullCheck(book);
Text version of Visibility Problem 4

Place this main method in InventoryDriver, with import cs1302.books.Book; already present.

addItem checks its argument and sets the supplied product's serial number to 15. nullCheck only rejects a null argument value.

Source file: cs1302/inventory/InventoryDriver.java

Obtain a manager and create a book, then call addItem to set that book's serial number. Print the resulting serial number, 15. Keep all existing visibilities unchanged.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

InventoryManager manager = InventoryManager.getManager();
Book book = new Book("LOTR");

Block B

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {

Block C

manager.addItem(book);

Block D

System.out.println(book.getSerial());

Block E

} // main

Block F

InventoryManager.nullCheck(book);
Sample solution for Visibility Problem 4

Block order: B, A, C, D, E.

Indentation levels: 0, 1, 1, 1, 0.

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {
    InventoryManager manager = InventoryManager.getManager();
    Book book = new Book("LOTR");
    manager.addItem(book);
    System.out.println(book.getSerial());
} // main

InventoryDriver and InventoryManager share a package, so the package private addItem method is accessible from this caller. Its Java declaration has no access modifier; UML denotes this visibility with ~. The private nullCheck alternative produces a compile-time error: sharing a package does not permit access to that private method. The two initializations share a block because either could occur first.

Problem 5: Use a Public Method of a Package Private Class

Use the Utility class shown below.

min returns with the smaller value. No other Utility class is available. The supplied alternative package block includes an import, so its failure concerns accessibility rather than a missing import.

Source file: cs1302/inventory/UtilityDriver.java

Assemble UtilityDriver.java to print 14 using Utility.min. Choose the caller's package so that access is permitted. Do not change Utility or add imports.

Unused Blocks
Solution Construction

Text version of Visibility Problem 5

Use the Utility class shown below.

min returns with the smaller value. No other Utility class is available. The supplied alternative package block includes an import, so its failure concerns accessibility rather than a missing import.

Source file: cs1302/inventory/UtilityDriver.java

Assemble UtilityDriver.java to print 14 using Utility.min. Choose the caller's package so that access is permitted. Do not change Utility or add imports.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

/** Demonstrates visibility from the chosen package. */
public class UtilityDriver {

Block B

} // UtilityDriver

Block C

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {
    long smaller = Utility.min(14, 15);
    System.out.println(smaller);
} // main

Block D

package cs1302.inventory;

Block E

package cs1302.books;

import cs1302.inventory.Utility;
Text version of Visibility Problem 5

Use the Utility class shown below.

min returns with the smaller value. No other Utility class is available. The supplied alternative package block includes an import, so its failure concerns accessibility rather than a missing import.

Source file: cs1302/inventory/UtilityDriver.java

Assemble UtilityDriver.java to print 14 using Utility.min. Choose the caller's package so that access is permitted. Do not change Utility or add imports.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

/** Demonstrates visibility from the chosen package. */
public class UtilityDriver {

Block B

} // UtilityDriver

Block C

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {
    long smaller = Utility.min(14, 15);
    System.out.println(smaller);
} // main

Block D

package cs1302.inventory;

Block E

package cs1302.books;

import cs1302.inventory.Utility;
Sample solution for Visibility Problem 5

Block order: D, A, C, B.

Indentation levels: 0, 0, 1, 0.

package cs1302.inventory;
/** Demonstrates visibility from the chosen package. */
public class UtilityDriver {
    /**
     * Demonstrate visibility using the supplied arguments.
     * @param args command-line arguments
     */
    public static void main(String[] args) {
        long smaller = Utility.min(14, 15);
        System.out.println(smaller);
    } // main
} // UtilityDriver

The correct caller is in cs1302.inventory, where the package private Utility class is accessible. Its public static method can then be called as Utility.min(14, 15). The alternative places the caller in cs1302.books and tries to import Utility. That import and use produce compile-time errors: a public method does not make its declaring class accessible from another package.

Problem 6: Obtain a Manager with a Private Constructor

Place this main method in ManagerDriver. It imports InventoryManager from cs1302.inventory.

Inside InventoryManager, getManager executes return new InventoryManager();. requestPurchase accepts a reference to a product object and returns without a value; it rejects null.

Source file: cs1302/books/ManagerDriver.java

Obtain a new manager through its public static method, then supply a reference to a new book in a call to requestPurchase. Keep the constructor private and leave all declarations in their existing packages.

Unused Blocks
Solution Construction

Text version of Visibility Problem 6

Place this main method in ManagerDriver. It imports InventoryManager from cs1302.inventory.

Inside InventoryManager, getManager executes return new InventoryManager();. requestPurchase accepts a reference to a product object and returns without a value; it rejects null.

Source file: cs1302/books/ManagerDriver.java

Obtain a new manager through its public static method, then supply a reference to a new book in a call to requestPurchase. Keep the constructor private and leave all declarations in their existing packages.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

InventoryManager manager = new InventoryManager();

Block B

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {

Block C

InventoryManager manager = InventoryManager.getManager();

Block D

} // main

Block E

manager.requestPurchase(new Book("LOTR"));
Text version of Visibility Problem 6

Place this main method in ManagerDriver. It imports InventoryManager from cs1302.inventory.

Inside InventoryManager, getManager executes return new InventoryManager();. requestPurchase accepts a reference to a product object and returns without a value; it rejects null.

Source file: cs1302/books/ManagerDriver.java

Obtain a new manager through its public static method, then supply a reference to a new book in a call to requestPurchase. Keep the constructor private and leave all declarations in their existing packages.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

InventoryManager manager = new InventoryManager();

Block B

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {

Block C

InventoryManager manager = InventoryManager.getManager();

Block D

} // main

Block E

manager.requestPurchase(new Book("LOTR"));
Sample solution for Visibility Problem 6

Block order: B, C, E, D.

Indentation levels: 0, 1, 1, 0.

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {
    InventoryManager manager = InventoryManager.getManager();
    manager.requestPurchase(new Book("LOTR"));
} // main

The private constructor is accessible inside InventoryManager, where getManager creates the manager object. That public static method returns with a reference value, which the caller stores in manager. It does not return with a copy of the manager object. Direct construction from ManagerDriver produces a compile-time error even though the class itself is public. The reference value supplied to requestPurchase is passed by value, not by reference.

Problem 7: Use Protected Access without Inheritance

Use the classes shown below.

Both classes are imported in the supplied code, regardless of which caller package you choose.

Source file: cs1302/inventory/SerialDriver.java

Assemble SerialDriver.java to set the book's serial number to 21 and print it. Choose the caller's package so the protected method call is permitted. SerialDriver must extend only Object; do not add an extends Product declaration or change existing visibilities.

Unused Blocks
Solution Construction

Text version of Visibility Problem 7

Use the classes shown below.

Both classes are imported in the supplied code, regardless of which caller package you choose.

Source file: cs1302/inventory/SerialDriver.java

Assemble SerialDriver.java to set the book's serial number to 21 and print it. Choose the caller's package so the protected method call is permitted. SerialDriver must extend only Object; do not add an extends Product declaration or change existing visibilities.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

package cs1302.books;

Block B

package cs1302.inventory;

Block C

import cs1302.books.Book;
import cs1302.inventory.Product;

/** Demonstrates visibility from the chosen package. */
public class SerialDriver {

Block D

} // SerialDriver

Block E

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {
    Product product = new Book("LOTR");
    product.setSerial(21);
    System.out.println(product.getSerial());
} // main
Text version of Visibility Problem 7

Use the classes shown below.

Both classes are imported in the supplied code, regardless of which caller package you choose.

Source file: cs1302/inventory/SerialDriver.java

Assemble SerialDriver.java to set the book's serial number to 21 and print it. Choose the caller's package so the protected method call is permitted. SerialDriver must extend only Object; do not add an extends Product declaration or change existing visibilities.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

package cs1302.books;

Block B

package cs1302.inventory;

Block C

import cs1302.books.Book;
import cs1302.inventory.Product;

/** Demonstrates visibility from the chosen package. */
public class SerialDriver {

Block D

} // SerialDriver

Block E

/**
 * Demonstrate visibility using the supplied arguments.
 * @param args command-line arguments
 */
public static void main(String[] args) {
    Product product = new Book("LOTR");
    product.setSerial(21);
    System.out.println(product.getSerial());
} // main
Sample solution for Visibility Problem 7

Block order: B, C, E, D.

Indentation levels: 0, 0, 1, 0.

package cs1302.inventory;
import cs1302.books.Book;
import cs1302.inventory.Product;

/** Demonstrates visibility from the chosen package. */
public class SerialDriver {
    /**
     * Demonstrate visibility using the supplied arguments.
     * @param args command-line arguments
     */
    public static void main(String[] args) {
        Product product = new Book("LOTR");
        product.setSerial(21);
        System.out.println(product.getSerial());
    } // main
} // SerialDriver

Within cs1302.inventory, the protected setSerial method is accessible from SerialDriver even though that class is not a subclass of Product. Moving this caller to cs1302.books produces a compile-time error at product.setSerial(21). Sharing a package with Book does not mean sharing the package that declares setSerial; that declaration is in Product. The object's runtime class does not change the caller's location.

Problem 8: Check the Qualifying Expression for Protected Access

Work inside Book in cs1302.books. Its superclass Product is imported from cs1302.inventory.

The supplied other argument refers to a different book object. Both other and the local variable product will refer to that same object, but their declared types differ.

Source file: cs1302/books/Book.java

Assemble updateSerials inside Book. Copy the reference value from other into a Product variable named product, then set this book's serial number to 10 and the other book's serial number to 20. Use a qualifying expression permitted by the protected-access rule; do not change either variable's declared type.

Unused Blocks
Solution Construction

Text version of Visibility Problem 8

Work inside Book in cs1302.books. Its superclass Product is imported from cs1302.inventory.

The supplied other argument refers to a different book object. Both other and the local variable product will refer to that same object, but their declared types differ.

Source file: cs1302/books/Book.java

Assemble updateSerials inside Book. Copy the reference value from other into a Product variable named product, then set this book's serial number to 10 and the other book's serial number to 20. Use a qualifying expression permitted by the protected-access rule; do not change either variable's declared type.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

this.setSerial(10);
other.setSerial(20);

Block B

this.setSerial(10);
product.setSerial(20);

Block C

Product product = other; // Copy the reference value.

Block D

} // updateSerials

Block E

/**
 * Demonstrate permitted protected access from this subclass.
 * @param other non-null reference to a book object
 */
public void updateSerials(Book other) {
Text version of Visibility Problem 8

Work inside Book in cs1302.books. Its superclass Product is imported from cs1302.inventory.

The supplied other argument refers to a different book object. Both other and the local variable product will refer to that same object, but their declared types differ.

Source file: cs1302/books/Book.java

Assemble updateSerials inside Book. Copy the reference value from other into a Product variable named product, then set this book's serial number to 10 and the other book's serial number to 20. Use a qualifying expression permitted by the protected-access rule; do not change either variable's declared type.

Write the letters of the correct blocks in order and give each block an indentation level. Leave incorrect blocks unused and preserve relative indentation within each block.

Block A

this.setSerial(10);
other.setSerial(20);

Block B

this.setSerial(10);
product.setSerial(20);

Block C

Product product = other; // Copy the reference value.

Block D

} // updateSerials

Block E

/**
 * Demonstrate permitted protected access from this subclass.
 * @param other non-null reference to a book object
 */
public void updateSerials(Book other) {
Sample solution for Visibility Problem 8

Block order: E, C, A, D.

Indentation levels: 0, 1, 1, 0.

/**
 * Demonstrate permitted protected access from this subclass.
 * @param other non-null reference to a book object
 */
public void updateSerials(Book other) {
    Product product = other; // Copy the reference value.
    this.setSerial(10);
    other.setSerial(20);
} // updateSerials

The access occurs inside Book, a subclass in a different package from the declaring class Product. For protected instance member access through a qualifying expression here, that expression's compile-time type must be Book or a subclass of Book. other meets this requirement; product does not, even though both variables refer to the same object. The alternative therefore produces a compile-time error. The two assignments share a block because they affect different book objects and can occur in either order; neither assignment changes a reference variable.

Runnable Sample Solutions

The simple/src directory contains the simplified Book from Problems 1–3, including the copy constructor added in Problem 2. The extended/src directory contains Book extends Product and the callers from Problems 4–8. Compile these source directories separately: they intentionally contain different versions of Book.

Bundle

Execute the command below to download and extract the files:

bundle1302 visibility-parsons
- downloading cs1302-visibility-parsons bundle...
- verifying integrity of downloaded files using sha256sum...
- extracting downloaded archive...
- removing intermediate files...
subdirectory cs1302-visibility-parsons successfully created