Java puzzle 28: Improving encapsulation

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 
>

If the following code is compiled and run, it writes [Orange, Apple, Mango, Cherry] to the standard output. By adding cherry to the fruit’s list, it’s clear that the class TestFruit is able to modify the fruit’s list. How can we improve the encapsulation of the class Fruit to prevent other classes from removing and adding elements to it? To achieve the previous goal, replace the statement return fruits; at line 27 with only one other statement.
As a result of that this code writes the original elements, namely [Orange, Apple, Mango] to the standard output.
What is that statement?

Java puzzle 28: Improving encapsulation

Level: Hard

import java.util.ArrayList;

public class TestFruit
{
  public static void main(String[] args)
  {
    Fruit fruit = new Fruit();
    fruit.getFruits().add("Cherry");
    System.out.print(fruit.getFruits());
  }
}
class Fruit
{
  private ArrayList<String> fruits;
  {
    fruits = new ArrayList<>();
    fruits.add("Orange");
    fruits.add("Apple");
    fruits.add("Mango");
  }
  
  public ArrayList<String> getFruits()
  {
    /*  replace the following statement
     *  with only one statement
     */
    return fruits;
  }
}
Author: Sar Maroof

Answer explanation

Adding and removing elements  from outside the class can be prevented by returning a copy of the list as follows.
Replace the statement at line 27: return fruits; with the following statement

return new ArrayList(fruits);
You can also return a clone of the ArrayList as follows.
return (ArrayList<String>) fruits.clone();

In every situation a programmer needs to make the choice that fits his/her needs, there might be also other solutions. I don’t get to the details of the choices, because that depends on the cases. What is presented here could be a simple solution! After all this is a puzzle that shows some idea’s and tricks to learn.

The second edition of Learn Java and Master Writing Code is easy to understand, organized to learn Java voor beginners and it guides readers to master Java code by solving more than 100 exercises and assignments. This book explains each chapter properly before starting with the exercises and the assignments. Available on Amazon. See inside the book here!




Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *