39,59 €
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 422
Veröffentlichungsjahr: 2017
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2017
Production reference: 1250317
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78728-284-1
www.packtpub.com
Author
Gastón C. Hillar
Reviewer
Daniel Mühlbachler
Acquisition Editor
Frank Pohlmann
Content Development Editor
Radhika Atitkar
Technical Editor
Bhagyashree Rai
Copy Editor
Tom Jacob
Project Coordinator
Remzil Nisha Dcruz
Proofreader
Safis Editing
Indexer
Tejal Daruwale Soni
Graphics
Kirk D'Penha
Production Coordinator
Melwyn Dsa
Gastón C. Hillar is Italian and has been working with computers since he was 8 years old. In the early 80s, he began programming with the legendary Texas TI-99/4A and Commodore 64 home computers. Gastón has a bachelor's degree in computer science (he graduated with honors). He also holds an MBA (he graduated with an outstanding thesis). At present, Gastón is an independent IT consultant and a freelance author who is always looking for new adventures around the world.
He was a senior contributing editor at Dr. Dobb's and has written more than a hundred articles on software development topics. He has received the prestigious Intel® Black Belt Software Developer award eight times. He has written many articles about Java for Oracle Java Magazine. Gastón was also a former Microsoft MVP in technical computing.
He is a guest blogger at Intel® Software Network (http://software.intel.com). You can reach him at <[email protected]> and follow him on Twitter at http://twitter.com/gastonhillar. Gastón's blog is http://csharpmulticore.blogspot.com.
He lives with his wife, Vanesa, and his two sons, Kevin and Brandon.
At the time of writing this book, I was fortunate enough to work with an excellent team at Packt Publishing, whose contributions vastly improved the presentation of this book. Dominic Shakeshaft and Frank Pohlmann allowed me to provide ideas to develop this book, and I jumped into the exciting project of teaching object-oriented and functional programming with Java 9 using JShell as the main tool. My conversations with Frank helped me realize my vision for this book and create a robust table of contents. Radhika Atitkar provided many sensible suggestions regarding the text, the format, and the flow. The reader will notice her great work. I would like to thank my technical reviewers and proofreaders for their thorough reviews and insightful comments. I was able to incorporate some of the knowledge and wisdom they have gained in their many years in the software development industry. This book was possible because they gave valuable feedback.
The process of writing a book requires a huge amount of lonely hours. I wouldn't be able to write a book without dedicating some time to play soccer against my sons, Kevin and Brandon, and my nephew, Nicolas. Of course, I never won a match. However, I did score a few goals.
Daniel Mühlbachler got interested in computer science shortly after entering high school, where he later developed web applications as part of a scholarship system for outstanding pupils.
He has a profound knowledge of web development (PHP, HTML, CSS/LESS, and AngularJS), and he has worked with a variety of other programming languages and systems, such as Java/Groovy, Grails, Objective-C and Swift, Matlab, Julia, C (with Cilk), Node.js, and Linux servers.
Furthermore, he works with some database management systems based on SQL and also some NoSQL systems, such as MongoDB and SOLR; this is also reflected in several projects that he is currently involved in at Catalysts GmbH.
After studying abroad as an exchange student in the United Kingdom, he completed his bachelor's degree at the Johannes Kepler University in Linz, Austria, with a thesis on aerosol satellite data processing for mobile visualization; this is where he also became familiar with processing large amounts of data.
Daniel enjoys solving challenging problems and is always keen on working with new technologies, especially those related to the fields of big data, functional programming, optimization, and NoSQL databases.
More detailed information about his experience, as well as his contact details, can be found at www.muehlbachler.org and www.linkedin.com/in/danielmuehlbachler.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787282848. If you'd like to join our team of regular reviewers, you can e-mail us at <[email protected]>. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
I dedicate this book to my sons, Kevin and Brandon, and my wife, Vanesa
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.
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, dives 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, dives 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.
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.
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.
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 <[email protected]>, 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.
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.
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:
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:
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!
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.
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 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 <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
In this chapter, we will start our journey toward object-oriented programming with Java 9. You 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 their results: JShell. This utility will make it easy for you to learn object-oriented programming. We will do the following:
In this book, you will learn to take advantage of all the object-oriented features included in the Java programming language version 9, known as Java 9. Some of the examples might be compatible with previous Java versions, such as Java 8, Java 7, and Java 6, but it is essential to use Java 9 or later because this version is not backwards compatible. We won't write code that is backwards compatible with previous Java versions because our main goal is to work with Java 9 or later and to use its syntax and all of its new features.
Most of the time, we won't use any IDE (Integrated Development Environment), and we will take advantage of JShell and many other utilities included in the JDK. However, you can use any IDE that provides a Java 9 REPL to work with all the examples. You will understand the benefits of working with a REPL in the next sections. You will definitely benefit from an IDE in the last chapter where you will explore the new modularity features introduced with Java 9.
You don't need any previous experience with the Java programming language to work with the examples in the book and learn how to model and create object-oriented code with Java 9. If you have some experience with C#, C++, Python, Swift, Objective-C, Ruby, or JavaScript, you will be able to easily learn Java's syntax and understand the examples. Many modern programming languages have been borrowing features from Java and vice versa. Therefore, any knowledge of these languages will be extremely useful.
In this chapter, we will install the required software on Windows, macOS, or Linux. We will understand the benefits of working with a REPL, specifically, JShell, to learn object-oriented programming. We will learn how to run Java 9 code in the JShell and how to load the source code samples in the REPL. Finally, we will learn how to run Java code on Windows, macOS, and Linux from the command line or terminal.
We must download and install the latest version of JDK 9 (Java Development Kit 9) for our operating system from https://jdk9.java.net/download/. We must accept the license agreement for Java to download the software.
As happened with previous versions, JDK 9 is available on many different platforms, including but not limited to the following:
Once we have completed the installation for the appropriate version of JDK 9 based on our operating system, we can add the bin sub-folder of the folder in which JDK 9 has been installed to the PATH environment variable. This way, we would be able to launch the different utilities from any folder in which we are located.
If we don't add the bin sub-folder of the folder in which JDK 9 has been installed to the PATH environment variable in our operating system, we will always have to use the full path to the bin sub-folder when executing the commands. In the next instructions to launch the different Java command-line utilities, we will assume that we are located in this bin sub-folder or that the PATH environment variable includes it.
Once we have installed JDK 9, and added the bin folder to the PATH environment variable, we can run the following command in Windows Command Prompt or in macOS or Linux Terminal:
The previous command will display the current version for the primary Java compiler included in the JDK that compiles Java source code into Java bytecodes. The version number should start with 9, as shown in the next sample output:
If the results of the previous command display a version number that doesn't start with 9, we must check whether the installation completed successfully. In addition, we have to make sure that the PATH environment variable doesn't include paths to previous versions of the JDK and that it includes the bin folder for the recently installed JDK 9.
Now, we are ready to launch JShell. Run the following command in Windows Command Prompt or in macOS or Linux Terminal:
The previous command will launch JShell, display a welcome message that includes the JDK version being used, and the prompt will change to jshell>. Whenever we see this prompt, it means we are still in JShell. The following screenshot shows JShell running in a Terminal window on macOS.
If we want to leave JShell at any time, we just need to press Ctrl + D in a Mac. Another option is to enter /exit and press Enter.
Java 9 introduced an interactive REPL command-line environment named JShell. This tool allows us to execute Java code snippets and get immediate results. We can easily write code and see the results of its execution without having to create a solution or project. We don't have to wait for the project to finish the build process to check the results of executing many lines of code. JShell, as any other REPL, facilitates exploratory programming, that is, we can easily and interactively try and debug different algorithms and structures.
If you have worked with other programming languages that provide a REPL or an interactive shell such as Python, Scala, Clojure, F#, Ruby, Smalltalk, and Swift among many others, you already know the benefits of working with a REPL.
For example, imagine that we have to interact with an IoT (Internet of Things) library that provides Java bindings. We have to write Java code to use the library to control a drone, also known as a UAV (Unmanned Aerial Vehicle). The drone is an IoT device that interacts with many sensors and actuators, including digital electronic speed controllers linked to engines, propellers, and servomotors.
We want to be able to write a few lines of code to retrieve data from sensors and control the actuators. We just need to make sure things work as explained in the documentation. We want to make sure that the values read from the altimeter change when we move the drone. JShell provides us with the appropriate tool to start interacting with the library in a few seconds. We just need to launch JShell, load the library, and start writing Java 9 code in the REPL. With previous Java versions, we would have needed to create a new project from scratch and write some boilerplate code before we could start writing the first lines of code that interacted with the library. JShell allows us to start working faster and reduces the need to create an entire skeleton to start running Java 9 code. JShell allows interactive exploration ofAPIs (Application Programming Interfaces) from a REPL.
We can enter any Java 9 definition in JShell. For example, we can declare methods, classes, and variables. We can also enter Java expressions, statements, or imports. Once we have entered the code to declare a method, we can enter a statement that uses the previously defined method and see the results of the execution.
JShell allows us to load source code from a file, and therefore, you will be able to load the source code samples included in this book and evaluate them in JShell. Whenever we have to work with source code, you will know the folder and the file from which you can load it. In addition, JShell allows us to execute JShell commands. We will learn about the most useful commands later, in this chapter.
JShell allows us to call the System.out.printf method to easily format output we want to print. We will take advantage of this method in our sample code.
JShell disables some features from Java 9 that aren't useful in the interactive REPL. Whenever we have to work with these features in JShell, we will make it clear that JShell will disable them and we will explain their effects.
The semicolon (;) is optional at the end of a statement in JShell. However, we will always use a semicolon at the end of each statement because we don't want to forget that we must use semicolons when we write real-life Java 9 code in projects and solutions. We will only omit the semicolon at the end of a statement when we enter expressions to be evaluated by JShell.
For example, the following two lines are equivalent and both of them will print "Object-Oriented Programming rocks with Java 9!" as a result of their execution in JShell. The first line doesn't include a semicolon (;) at the end of the statement and the second line includes the semicolon (;). We will always use the semicolon (;) as in the second line, to keep consistency.
The following screenshot shows the results of executing the two lines in JShell running on Windows 10:
In some examples, we will take advantage of the fact that JShell provides us networking access. This feature is extremely useful to interact with Web Services. However, you have to make sure that you don't have JShell blocked in your firewall configuration.
Unluckily, at the time I was writing this book, JShell didn't include syntax highlighting features. However, you will learn how to use our favorite editor to write and edit code that we can then execute in JShell.
By default, JShell provides a set of common imports and we can use the import statement to import the necessary types from any additional package we might need to run our code snippets. We can enter the following command in JShell to list all the imports:
The following lines show the results of the previous command:
As happens when we write Java code outside of JShell, we don't need to import the types from the java.lang package because they are imported by default and they aren't listed when we run the /imports command in JShell. Thus, by default, JShell provides us access to all the types in the following packages:
JShell provides auto-completion features. We just need to press the Tab key whenever we want to have assistance from the auto-complete feature, as done when we work with the Windows Command Prompt or the Terminal in macOS or Linux.
Sometimes, there are too many options that start with the first characters we entered. In these cases, JShell provides us with a list of all the available options to provide us help. For example, we can enter S and press the Tab key. JShell will list all the types imported from the previously listed packages that start with an S. The following screenshot shows the results in JShell:
We want to enter System. Considering the previous list, we will just enter Sys to make sure that System is the only option that starts with Sys. Basically, we are cheating to understand how auto-completion works in JShell. Enter Sys and press the Tab key. JShell will display System.
Now, enter a dot (.) followed by an o (you will have System.o) and press the Tab key. JShell will display System.out.
Next, enter a dot (.) and press the Tab key. JShell will display all the public methods declared in System.out. After the list, JShell will include System.out. again to allow us to continue entering our code. The following screenshot shows the results in JShell:
Enter printl and press the Tab key. JShell will complete to System.out.println(, that is, it will add an n and open parenthesis ((). This way, we just have to enter the arguments for the method because there was just one method that started with printl. Enter "Auto-complete is helpful in JShell"); and press Enter. The following line shows the complete statement:
The following screenshot shows the results in JShell after running the previous line:
