Java 9 with JShell
上QQ阅读APP看书,第一时间看更新

Preface

Java is definitely one of the most popular programming languages of this century. However, whenever we had to quickly explore new algorithms or new application domains, Java didn't provide us with a simple way of executing code snippets and print the results. As a result of this limitation, many developers started working with other programming languages that offered a REPL (Read-Evaluate-Print-Loop) utility, such as Scala and Python. However, many times, it was necessary to go back to Java after the exploratory phase finished and the requirements and the algorithms were clear.

Java 9 introduces JShell, a new utility that allows us to easily run Java 9 code snippets and print the results. This utility is a REPL, and makes it easy for us to work with Java as developers do with Scala and Python. JShell makes it easier to learn Java 9 and its most important features.

Object-oriented programming, also known as OOP, is a required skill in absolutely every modern software developer job. It makes a lot of sense because OOP allows you to maximize code reuse and minimize maintenance costs. However, learning object-oriented programming is challenging because it includes too many abstract concepts that require real-life examples to be easy to understand. In addition, object-oriented code that doesn't follow best practices can easily become a maintenance nightmare.

Java is a multi-paradigm programming language, and one of its most important paradigms is OOP. If you want to work with Java 9, you need to master OOP in Java. In addition, as Java 9 also grabs nice features found in functional programming languages, it is convenient to know how to mix OOP code with functional programing code.

This book will allow you to develop high-quality reusable object-oriented code in Java 9 with JShell. You will learn the object-oriented programming principles and how Java 9 implements them, combined with modern functional programming techniques. You will learn how to capture objects from real-world elements and create object-oriented code that represents them. You will understand Java's approach towards object-oriented code. You will maximize code reuse and reduce maintenance costs. Your code will be easy to understand and it will work with representations of real-life elements.

In addition, you will learn how to organize code using the new modularity feature introduced in Java 9, and you will be ready to create complex applications.

What this book covers

Chapter 1, JShell – A Read-Evaluate-Print-Loop for Java 9, starts our journey towards object-oriented programming with Java 9. We will learn how to launch and work with a new utility introduced with Java 9 that will allow us to easily run Java 9 code snippets and print its results: JShell. This utility will make it easy for us to learn object-oriented programming.

Chapter 2, Real-World Objects to UML Diagrams and Java 9 via JShell, teaches how to recognize objects from real-life situations. We will understand that working with objects makes it easier to write code that is easier to understand and reuse. We will learn how to recognize real-world elements and translate them into the different components of the object-oriented paradigm supported in Java. We will start organizing classes with UML (Unified Modeling Language) diagrams.

Chapter 3, Classes and Instances, shows that classes represent blueprints or templates to generate the objects, which are also known as instances. We will design a few classes that represent blueprints of real-life objects. We will learn about an object's life cycle. We will work with many examples to understand how initialization works. We will declare our first class to generate a blueprint for objects. We will customize its initialization and test its personalized behavior in action with live examples in the JShell. We will understand how the garbage collection works.

Chapter 4, Encapsulation of Data, teaches you the different members of a class in Java 9 and how they are reflected in members of the instances generated from a class. We will work with instance fields, class fields, setters, getters, instance methods, and class methods. We will generate computed properties with setters and getters. We will take advantage of access modifiers to hide data. We will use static fields to create values shared by all the instances of a class.

Chapter 5, Mutable and Immutable Classes, introduces the differences between mutating and non-mutating objects. First, we will create a mutable class, and then we will build an immutable version of this class. We will learn the advantages of non-mutating objects when writing concurrent code.

Chapter 6, Inheritance, Abstraction, Extension, and Specialization, discusses how to take advantage of simple inheritance to specialize or extend a base class. We will design many classes from top to bottom and we will use chained constructors. We will use UML diagrams to design classes that inherit from another class. We will code the classes in the interactive JShell. We will override and overload methods. We will run code to understand how all the things we code work.

Chapter 7, Members Inheritance and Polymorphism, teaches you how to control whether subclasses can or cannot override members. We will take advantage of one of the most exciting object-oriented features: polymorphism. We will take advantage of JShell to easily understand typecasting. We will declare methods that perform operations with instances of classes.

Chapter 8, Contract Programming with Interfaces, introduces how interfaces work in combination with classes in Java 9. The only way to have multiple inheritance in Java 9 is through the usage of interfaces. We will learn about the declaration and combination of multiple blueprints to generate a single instance. We will declare interfaces with different types of requirements. Then, we will declare many classes that implement the created interfaces. We will combine interfaces with classes to take advantage of multiple inheritance in Java 9. We will combine inheritance for interfaces and inheritance for classes.

Chapter 9, Advanced Contract Programming with Interfaces, pes deeper in to contract programming with interfaces. We will work with methods that receive interfaces as arguments. We will understand how downcasting works with interfaces and classes and we will treat instances of an interface type as a different subclass. JShell will allow us to easily understand the complexities of typecasting and downcasting. We will work with more complex scenarios in which we will combine class inheritance with interface inheritance.

Chapter 10, Maximization of Code Reuse with Generics, introduces you to working with parametric polymorphism. We will learn how to maximize code reuse by writing code capable of working with objects of different types, that is, instances of classes that implement specific interfaces or whose class hierarchy includes specific superclasses. We will work with interfaces and generics. We will create a class that works with a constrained generic type. We will use a generic class for multiple types, thanks to generics.

Chapter 11, Advanced Generics, pes deeper in parametric polymorphism. We will declare a class that works with two constrained generic types. We will use a generic class with two generic type parameters in JShell. We will generalize existing classes by taking advantage of generics in Java 9.

Chapter 12, Object-Oriented, Functional Programming, and Lambda Expressions, discusses that functions are first-class citizens in Java 9. We will work with functional interfaces within classes. We will use many functional programming features included in Java 9 and combine them with everything we learned in the previous chapters about object-oriented programming. This way, we will be able to use the best of both worlds. We will analyze the differences between the imperative and functional programming approach for many algorithms. We will take advantage of lambda expressions and combine map operations with reduce.

Chapter 13, Modularity in Java 9, puts together all the pieces of the object-oriented puzzle. We will refactor existing code to take advantage of object-oriented programming. We will understand the usage of modular source code in Java 9. We will work with modules to create a new Java 9 solution, organize object-oriented code with the new modularity in Java 9, and learn many techniques of debuggingobject-oriented code.

What you need for this book

You will need a computer with a dual-core CPU and at least 4 GB RAM, capable of running JDK 9 Windows Vista SP2, Windows 7, Windows 8.x, Windows 10 or higher, or macOS 10.9 or higher, and any Linux distribution supported by JDK 9. Any IoT device capable of running JDK 9 will also be useful.

Who this book is for

This book can be understood by anyone who is a graduate of computer science or someone who has just begun working as a software engineer. Basically, an understanding of an object-oriented programming language such as Python, C++, or indeed, an earlier Java version, is sufficient. It would be helpful to have participated in the full product cycle of a software engineering project.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Code words in text are shown as follows: "JShell allows us to call the System.out.printf method to easily format output we want to print."

A block of code is set as follows:

double getGeneratedRectangleHeight() {
    final Rectangle rectangle = new Rectangle(37, 87);
    return rectangle.height; 
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

double getGeneratedRectangleHeight() {
    final Rectangle rectangle = new Rectangle(37, 87);
    return rectangle.height; 
}

Any command-line input or output is written as follows:

javac -version

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Click on Accept and then click on Exit."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Java-9-with-JShell. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/Java9withJShell_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.