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

Customizing constructors and initialization


We want to initialize instances of the Rectangle class with the width and height values for the new rectangle. In order to do so, we can take advantage of the previously introduced constructors. Constructors are special class methods that are automatically executed when we create an instance of a given type. Java runs the code within the constructor before any other code within a class.

We can define a constructor that receives both the width and height values as arguments, and use it to initialize the fields with the same names. We can define as many constructors as we want to, and therefore, we can provide many different ways of initializing a class. In this case, we just need one constructor.

The following lines create a Rectangle class and define a constructor within the class body. At this time, we aren't using access modifiers at all because we want to keep the class declaration as simple as possible. We will work with them later. The code...