0% found this document useful (0 votes)
31 views32 pages

Chapter 9

Uploaded by

202227269
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views32 pages

Chapter 9

Uploaded by

202227269
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

9.

1 Introduction

Object-oriented programming (OOP) ⇨ is a programming paradigm based on the concept of


"objects".

Programming paradigm: is a style of programming, a way of thinking about software construction.

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.

Reference variables can be declared without being initialized;

A local reference variable must reference an object before it can be used;

9.2 Defining Classes for Objects

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.

 In the class diagram, the data field is denoted as;

 In the class diagram, the constructor is denoted as;

2|Page
 In the class diagram, the method is denoted as

9.3 Example, Defining Classes and Creating Objects

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.

9.4 Constructing Objects Using Constructors

A Constructor ⇨ is a method that is automatically called when an object is created.

Constructors are a special kind of method. They have three peculiarities:

1. A constructor must have the same name as the class itself.

2. A constructor does not have a return type—not even void.


3. Constructors may not return any values.

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

No-arg Constructor ⇨ is a constructor that does not accept any arguments.

Parameterized Constructor ⇨ is a constructor that accepts arguments.

Default Constructor ⇨ is a constructor that is automatically created by the java compiler if no


constructors are explicitly defined.

1. It sets all of the object’s numeric fields to (0).

2. It sets all of the object’s Boolean fields to (false).


3. It sets all of the object’s reference variables to the special value (null).

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.

9.5 Accessing Objects via Reference Variables

An object’s data and methods can be accessed through the dot (.) operator via the object’s reference
variable.

9.5.1 Reference Variables and Reference Types

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:

9.5.2 Accessing an Object’s Data and Methods

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:

 objectRefVar.dataField references a data field in the object.


 objectRefVar.method(arguments) invokes a method on the object.

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.

9.5.3 Reference Data Fields and the null Value

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.

9.5.4 Differences between Variables of Primitive Types and Reference Types

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.

9.6 Using Classes from the Java Library

9.6.1 The Date Class

Java provides a system-independent encapsulation of date and time in the java.util.Date class.

8|Page
For example, the following code;

Constructors of Date class ⇨

 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);

Methods of Date class ⇨

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.

9.6.2 The Random Class

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.

For example, the following code;

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.

For example, the following code;

11 | P a g e
9.7 Static Variables, Constants, and Methods

9.7.1 Static Keyword

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.

9.7.2 Static Blocks

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.

Static blocks can be executed before constructors.

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.

9.7.3 Static Variables

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:

1. They can only directly call other static methods.

2. They can only directly access static data.

3. They cannot refer to this or super in any way.

 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:

9.8 Visibility Modifiers

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.

 Default or Package-Private ⇨ If no visibility modifier is used, then by default the classes,


methods, and data fields are accessible by any class in the same package.

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.

9.9 Data Field Encapsulation

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

9.10.1 Passing an Object to Method

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.

9.10.2 Returning an Object from Method

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:

Invoking circleArray[1]. getArea() involves two levels of referencing,

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.

The createCircleArray() method returns an array of CircleWithPrivateDataFields objects. The array is


passed to the printCircleArray() method, which displays the radius and area of each circle and the total
area of the circles.

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 ⇨

1. All data fields must be private.

2. There can’t be any mutator methods for data fields.


3. No accessor methods can return a reference to a data field that is mutable.

9.13 The Scope of Variables

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).

9.14.1 Using this to Reference Hidden Data Fields

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.

 A hidden instance variable can be accessed by using the keyword this.

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:

9.14 The Initializer Block

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.

There are 3 areas where we can use the initializer blocks ⇨

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.

 We can declare any datatype with the var keyword.


 You can use var keyword in a local variable declaration.

 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.

9.16 For-Each Loop

"for-each" loop, which is used exclusively to loop through elements in an array:

Limitations of for-each loop ⇨

 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:

 For-each cannot process two decision making statements at once:

31 | P a g e

You might also like