Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Quiz 15: Improve Encapsulation of Your Code

DZone's Guide to

Java Quiz 15: Improve Encapsulation of Your Code

Get caught up with the answer to the previous quiz on overloading methods, and try your hand at this quiz, which deals with improving the encapsulation of your code.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Before we start with this week's puzzle, here is the answer to Java Quiz 14: Overloading Methods.

The method writeValue(1, 2) invokes writeValue(int, int) because 1 and 2 are integers.
The method writeValue(int, int) doesn't exist. Therefore, writeValue(int, double)
is invoked instead of writeValue(int, Integer). The reason is that widening is preferred over boxing/unboxing. The correct answer is: D.

Here is the Java puzzle for today!

If the following code is compiled and run, it writes [David, Emma, Layla, Victoria] to the standard output.

By adding Victoria and removing Mike from the customer's list, it's clear that the class TestCustomer is able to modify the list.

How can we improve the encapsulation of the class Customer to achieve the following goals?

  1. Other classes should be allowed to display the customer's list.
  2. Other classes shouldn't be allowed to remove or add customers to the list.
import java.util.ArrayList;
 

public class TestCustomer
{
  public static void main(String[] args)
  {
    Customer customer = new Customer();
    customer.getCustomers().add("Victoria");
    customer.getCustomers().remove(2);
    System.out.print(customer.getCustomers());
  }
}


class Customer
{
  private ArrayList<String> customers;
  {
    customers = new ArrayList<>();
    customers.add("David");
    customers.add("Emma");
    customers.add("Mike");
    customers.add("Layla");
  }
  public ArrayList<String> getCustomers()
  {
    return customers;
  }
}

The correct answer and its explanation will be included in the next quiz in two weeks! For more Java quizzes, puzzles, and assignments, take a look at my site!

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,encapsulation ,optimization

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}