Book Image

Java 9 with JShell

By : Gaston C. Hillar
Book Image

Java 9 with JShell

By: Gaston C. Hillar

Overview of this book

The release of Java 9 has brought many subtle and not-so-subtle changes to the way in which Java programmers approach their code. The most important ones are definitely the availability of a REPL, known as JShell, which will make experiments and prototyping much more straightforward than the old IDE-based project-led approach. Another, more subtle change can be seen in the module system, which will lead to more modularized, maintainable code. The techniques to take full advantage of object-oriented code, functional programming and the new modularity features in Java 9 form the main subjects of this book. Each chapter will add to the full picture of Java 9 programming starting out with classes and instances and ending with generics and modularity in Java.
Table of Contents (23 chapters)
Java 9 with JShell
Credits
About the Author
Acknowledgement
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Index

Creating the immutable version of an existing mutable class


In the previous chapter, we created a mutable class named VirtualCreature. We provided setter methods to change the values for the hat, visibilityLevel, and birthYear fields. We were able to change the birthYear by calling the setAge method.

Virtual creatures change their age, hat, and visibility level after they evolve. When they evolve, they become a different creature, and therefore, it would make sense to generate a new instance after this evolution happens. Thus, we will create the immutable version of the VirtualCreature class and we will call it ImmutableVirtualCreature.

The following lines show the code for the new ImmutableVirtualCreature class. The code file for the sample is included in the java_9_oop_chapter_05_01 folder, in the example05_06.java file.

import java.time.Year;

public class ImmutableVirtualCreature {
    public final String name;
    public final int birthYear;
    public final String hat;
    public final...