Complex Numbers

Example 2-5 shows the definition of a class that represents complex numbers. You may recall from algebra class that a complex number is the sum of a real number and an imaginary number. The imaginary number i is the square root of -1. This ComplexNumber class defines two double fields, which represent the real and imaginary parts of the number. These fields are declared private, which means they can be used only within the body of the class; they are inaccessible outside the class. Because the fields are inaccessible, the class defines two accessor methods, real( ) and imaginary( ), that simply return their values. This technique of making fields private and defining accessor methods is called encapsulation. Encapsulation hides the implementation of a class from its users, which means that you can change the implementation without it affecting the users.

Notice that the ComplexNumber class doesn’t define any methods, other than the constructor, that set the values of its fields. Once a ComplexNumber object is created, the number it represents can never be changed. This property is known as immutability; it is often useful to design objects that are immutable like this.

ComplexNumber defines two add( ) methods and two multiply( ) methods that perform addition and multiplication of complex numbers. The difference between the two versions of each method is that one is an instance method and one is a class, or static, method. Consider the add( ) methods, for ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.