Chapter 9
Chapter 9
1 Introduction
A programming paradigm does not refer to a specific language but rather to a way to build a program
or a methodology to apply.
Data Hiding ⇨ is a software development technique in which the object hides its private fields from
code that is outside the class that the object is an instance of.
Only the class's methods may directly access and change the object’s internal data So, Code outside
the class must use the class's public methods to operate on an object's private fields.
An object (instance) represents an entity in the real world that can be distinctly identified or is an
executable copy of the class. An object is comprised of states (Data), and behaviors (Operations).
The state of an object (also known as its properties) is represented by data fields with their current
values.
A rectangle object has the data fields width and height, which are the properties that
characterize a rectangle.
1|Page
The behavior of an object (also known as its actions) is defined by methods. To invoke a method on an
object is to ask the object to perform an action.
A rectangle object may invoke getArea() to return its area and getPerimeter() to return its
perimeter.
A class is a blueprint, or contract that defines what an object’s data fields and methods will be.
An object is an instance of a class & objects of the same type are defined using a common class.
Creating an instance is referred to as instantiation.
A class provides a special methods, known as constructors, which are invoked to create a new object.
A constructor can perform any action, but constructors are designed to perform initializing
actions, such as initializing the data fields of objects.
The illustration of class templates and objects can be standardized using Unified Modeling Language
(UML) notation. This notation is called a class diagram.
2|Page
In the class diagram, the method is denoted as
I.e. a program that defines the Circle class and uses it to create objects. The program constructs three
circle objects with radius 1, 25, and 125 and displays the radius and area of each of the three circles.
3|Page
The program contains two classes. The first of these, TestSimpleCircle, is the main class. Its sole
purpose is to test the second class, SimpleCircle
You can put the two classes into one file, but only one class in the file can be a public class. Furthermore,
the public class must have the same name as the file name.
When you compile TestSimpleCircle.java, two class files TestSimpleCircle.class and SimpleCircle.class
are generated;
4|Page
As in creating an array, the new operator is used to create an object from the constructor: new
SimpleCircle() creates an object with radius 1 (line 5), new SimpleCircle(25) creates an object with
radius 25 (line 10), and new SimpleCircle(125) creates an object with radius 125 (line 15).
These three objects (referenced by circle1, circle2, and circle3) have different data but the same
methods. Therefore, you can compute their respective areas by using the getArea () method.
The data fields can be accessed via the reference of the object using circle1.radius, circle2.radius, and
circle3.radius, respectively.
The object can invoke its method via the reference of the object using circle1.getArea (),
circle2.getArea(), and circle3.getArea(), respectively.
4. Constructors are invoked using the new operator when an object is created.
Constructors can be overloaded (i.e., multiple constructors can have the same name but different
signatures), making it easy to construct objects with different initial data values.
To construct an object from a class, invoke a constructor of the class using the new operator:
5|Page
9.4.1 Types of Constructors
Copy Constructor ⇨ is a constructor that creates an object using another object of the same class.
Constructor Chaining ⇨ means that a constructor calls another constructor of same class.
An object’s data and methods can be accessed through the dot (.) operator via the object’s reference
variable.
Objects are accessed via the object’s reference variables, which contain references to the objects.
Such variables are declared using the following syntax:
A class is a reference type, which means that a variable of the class type can reference an instance of
the class.
6|Page
The following statement declares the variable myCircle to be of the Circle type:
The next statement creates an object and assigns its reference to myCircle:
The following statement combines the declaration of an object reference variable, the creation of
an object, and the assigning of an object reference to the variable:
After an object is created, its data can be accessed and its methods can be invoked using the dot
operator (.), also known as the object member access operator:
I.e. myCircle.radius references the radius in myCircle, and myCircle.getArea() invokes the getArea
method on myCircle.
The data field radius is referred to as an instance variable, because it is dependent on a specific
instance. For the same reason, the method getArea is referred to as an instance method, because you
can invoke it only on a specific instance.
If a data field of a reference type does not reference any object, the data field holds a special Java
value, null; null is a literal just like true and false.
7|Page
The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean
type, and \u0000 for a char type.
NullPointerException is a common runtime error. It occurs when you invoke a method on a reference
variable with a null value. Make sure you assign an object reference to the variable before invoking the
method through the reference variable.
For a variable of a primitive type, the value is of the primitive type; when you assign one variable to
another, the real value of one variable is assigned to the other variable.
For a variable of a reference type, the value is a reference to where an object is; when you assign one
variable to another, the reference of one variable is assigned to the other.
Java provides a system-independent encapsulation of date and time in the java.util.Date class.
8|Page
For example, the following code;
Date();
Date(int year, int month, int date);
Date(int year, int month, int date, int hrs, int min, int sec);
Date(long date);
Date(String s);
getYear();
Returns a value that is the result of subtracting 1900 from the year.
getMonth();
Returns a number representing the month & value returned is between 0 and 11.
getDate();
Returns the day of the month represented by this Date object.
getDay();
Returns the day of the week represented by this Date object & value returned is
between 0 and 6.
getHours();
Returns the hour represented by this Date object & value returned is between 0 and 23.
getMinutes();
Returns the number of minutes past the hour represented by this Date object & value
returned is between 0 and 59.
9|Page
getSeconds();
Returns the number of seconds past the minute represented by this Date object & value
returned is between 0 and 60.
getTime();
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by
this Date object.
setTime(long time);
Sets this Date object to represent a point in time that is time milliseconds after January 1,
1970 00:00:00 GMT.
To generate random numbers is to use the java.util.Random class, which can generate a random int,
long, double, float, and boolean value.
When you create a Random object, you have to specify a seed or use the default seed. A seed is a
number used to initialize a random number generator. If two Random objects have the same seed, they
will generate identical sequences of numbers.
10 | P a g e
9.6.3 The Point2D Class
Java API has a convenient Point2D class in the javafx.geometry package for representing a point in a
two-dimensional plane.
11 | P a g e
9.7 Static Variables, Constants, and Methods
The static keyword in Java is used to share the same variable or method of a given class. The users
can apply static keywords with variables, methods, blocks, and nested classes.
The static keyword belongs to the class than an instance of the class. The static keyword is used for
a constant variable or a method that is the same for every instance of a class.
The static keyword is a non-access modifier in Java that is applicable for the following ⇨
1. Blocks
2. Variables
3. Methods
4. Classes
When a member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object.
If you need to do the computation in order to initialize your static variables, you can declare a static
block that gets executed exactly once, when the class is first loaded.
Consider the following java program demonstrating the use of static blocks ⇨
12 | P a g e
Static blocks can be executed before main() method.
A class can have any number of static initialization blocks, and they can appear anywhere in the class
body. The runtime system guarantees that static initialization blocks are called in the order that they
appear in the source code.
When a variable is declared as static, then a single copy of the variable is created and shared among
all objects at the class level & store values for the variables in a common memory location. So, if one
object changes the value of a static variable, all objects of the same class are affected.
Consider the following java program demonstrating the use of static variables ⇨
13 | P a g e
9.7.4 Static Methods
When a method is declared with the static keyword, it is known as the static method. Methods declared
as static have several restrictions:
Consider the following java program demonstrating the restrictions on static methods ⇨
14 | P a g e
15 | P a g e
9.7.5 Static Classes
A class can be made static only if it is a nested class. We cannot declare a top-level class with a static
modifier but can declare nested classes as static. Nested static class doesn’t need a reference of Outer
class. In this case, a static class cannot access non-static members of the Outer class.
An instance of an Inner class cannot be created without an instance of the Outer class. Therefore, an
Inner class instance can access all of the members of its Outer class, without using a reference to the
Outer class instance.
The following are major differences between static nested classes and inner classes:
1. A static nested classes may be instantiated without instantiating its Outer class.
2. Inner classes can access both static and non-static members of the Outer class. A static classes
can access only the static members of the Outer class.
I.e. let’s modify the Circle class by adding a static variable numberOfObjects to count the number of
circle objects created. When the first object of this class is created, numberOfObjects is 1. When the
second object is created, numberOfObjects is 2.
16 | P a g e
The circle class, named CircleWithStaticMembers, is defined in the following code:
Instance methods (e.g., getArea()) and instance data (e.g., radius) can be used only after the instances
are created. They are accessed via a reference variable only.
Static methods (e.g., getNumberOfObjects()) and static data (e.g., numberOfObjects) can be accessed
from a reference variable or from their class name.
17 | P a g e
The TestCircleWithStaticMembers class, is defined to test the previous class:
Visibility modifiers (also known as access modifiers) is a Java keyword that can be used to specify
the visibility of a class and its members.
Public ⇨ the public access modifier is applied to classes, methods, and data fields; to denote
that they can be accessed by code inside a class or outside.
18 | P a g e
Private ⇨ the private access modifier is applied to methods, and data fields; to denote that
they can be accessed by code inside a class only.
I.e. illustrates how a public, default, and private data field or method in class C1 can be accessed from
a class C2 in the same package and from a class C3 in a different package.
To prevent direct modifications of data fields, you should declare the data fields private, using the
private modifier. This is known as data field encapsulation.
To make a private data field accessible, provide a getter (accessor) method to return its value; A getter
method has the following signature:
To enable a private data field to be updated, provide a setter (mutator) method to set a new value. A
setter method has the following signature:
19 | P a g e
I.e. let’s create a new circle class with a private data-field radius and its associated accessor and
mutator methods:
I.e., this is a client program that uses the Circle class to create a Circle object and modifies the radius
using the setRadius method.
20 | P a g e
9.10 Passing and Returning Objects from Methods
Passing an object to a method is to pass the reference of the object. A copy of the object is not passed,
just a pointer to the object.
When a method receives a reference variable as an argument, it is possible for the method to modify
the contents of the object referenced by the variable.
I.e. the following program demonstrates the difference between passing a primitive type value and
passing a reference value.
21 | P a g e
When passing an argument of a primitive data type, the value of the argument is passed. In this case,
the value of n (5) is passed to times. Inside the printAreas method, the content of times is changed; this
does not affect the content of n.
When passing an argument of a reference type, the reference of the object is passed. In this case, c
contains a reference for the object that is also referenced via myCircle. Therefore, changing the
properties of the object through c inside the printAreas method has the same effect as doing so outside
the method through the variable myCircle.
Methods can return references to objects; just as with passing arguments, a copy of the object is not
returned, only its address.
22 | P a g e
9.11 Array of Objects
An array can hold objects as well as primitive type values; an array of objects is actually an array of
reference variables.
The following statement declares and creates an array of ten Circle objects:
To initialize circleArray, you can use a for loop like this one:
I.e. the following program summarizes the areas of an array of circles. The program creates
circleArray, an array composed of five Circle objects; it then initializes circle radii with random values
and displays the total area of the circles in the array.
23 | P a g e
The program invokes createCircleArray() to create an array of five circle objects. The circle radii are
randomly generated using the Math.random() method.
24 | P a g e
9.12 Immutable Objects and Classes
You can define immutable classes to create immutable objects. The contents of immutable objects
cannot be changed.
If a class is immutable, then all its data fields must be private and it cannot contain public setter
methods for any data fields.
A class with all private data fields and no mutators is not necessarily immutable. For example, the
following Student class has all private data fields and no mutators, but it is not an immutable class.
As shown in the following code, the data field dateCreated is returned using the getDateCreated()
method. This is a reference to a Date object. Through this reference, the content for dateCreated can
be changed.
25 | P a g e
For a class to be immutable, it must meet the following requirements ⇨
The scope of instance and static variables is the entire class, regardless of where the variables are
declared.
A class’s variables and methods can appear in any order in the class. The exception is when a data field
is initialized based on a reference to another data field. In such cases, the other data field must be
declared first.
If a local variable has the same name as a class’s variable, the local variable takes precedence and the
class’s variable with the same name is hidden. i.e. the following program, x is defined both as an
instance variable and as a local variable in method.
26 | P a g e
9.14 The this Reference
The this keyword refers to the object itself. It can also be used inside a constructor to invoke another
constructor of the same class.
The this keyword is the name of a reference that an object can use to refer to itself. You can use the
this keyword to reference the object’s instance members.
I.e. the following code in (a) uses this to reference the object’s radius and invokes its getArea() method
explicitly. The this reference is normally omitted, as shown in (b).
I.e. a data field name is often used as the parameter name in a setter method for the data field. In this
case, the data field is hidden in the setter method. You need to reference the hidden data-field name in
the method in order to set a new value to it.
A hidden static variable can be accessed simply by using the ClassName.staticVariable reference.
27 | P a g e
9.14.2 Using this to Invoke a Constructor
The this keyword can be used to invoke another constructor of the same class. i.e., you can rewrite
the Circle class as follows:
In order to perform any operations while assigning values to an instance data member, an initializer
block is used. In simpler terms, the initializer block is used to declare/initialize the common part of
various constructors of a class.
The initializer block contains the code that is always executed whenever an instance is created and
it runs each time when an object of the class is created.
28 | P a g e
Initializer blocks are executed whenever the class is initialized and is always executed before the
constructor.
1. Constructors
2. Methods
3. Blocks
Instance Initialization Blocks or IIB are used to initialize instance variables. So firstly, constructor is
invoked and the java compiler copies the instance initializer block in the constructor after the first
statement super().
We can also have multiple IIBs in a single class. If the compiler finds multiple IIBs, then they all are
executed from top to bottom i.e. the IIB which is written at the top will be executed first.
You can have IIBs in parent class also. Instance Initialization Block code runs immediately after the call
to super() in a constructor. The compiler executes parents class’s IIB before executing current class’s
IIBs.
Consider the following java program demonstrating the execution of initializer block;
29 | P a g e
9.15 Var keyword
Var keyword detects automatically the datatype of a variable based on the surrounding context.
You cannot use var keyword in an instance and global variable declaration.
30 | P a g e
You cannot use var keyword as a Generic type.
You cannot use var keyword with the Generic type.
You cannot use var keyword without explicit initialization.
You cannot use var keyword with Lambda Expression.
You cannot use var keyword for method parameters and return type.
For-each loops are not appropriate when you want to modify the array:
For-each loops do not keep track of index. So we cannot obtain array index using For-Each loop:
For-each only iterates forward over the array in single steps:
31 | P a g e