0% found this document useful (0 votes)
4 views67 pages

Introduction To Java Programming and Data Structures

Chapter 9 of 'Introduction to Java Programming and Data Structures' covers the fundamentals of object-oriented programming (OOP) in Java, explaining the concepts of objects, classes, and constructors. It emphasizes the importance of encapsulation, visibility modifiers, and the distinction between instance and static members. Additionally, the chapter discusses garbage collection, the handling of reference types, and the creation and manipulation of objects and arrays in Java.

Uploaded by

wehadweda
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)
4 views67 pages

Introduction To Java Programming and Data Structures

Chapter 9 of 'Introduction to Java Programming and Data Structures' covers the fundamentals of object-oriented programming (OOP) in Java, explaining the concepts of objects, classes, and constructors. It emphasizes the importance of encapsulation, visibility modifiers, and the distinction between instance and static members. Additionally, the chapter discusses garbage collection, the handling of reference types, and the creation and manipulation of objects and arrays in Java.

Uploaded by

wehadweda
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

Introduction to Java Programming and

Data Structures
Thirteenth Edition

Chapter 9
Objects and Classes

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Motivations
After learning the preceding chapters, you are capable of
solving many programming problems using selections,
loops, methods, and arrays.
However, these Java features are not sufficient for
developing graphical user interfaces and large scale
software systems.
Suppose you want to develop a graphical user interface
as shown below. How do you program it?

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


OO Programming Concepts
 Object-oriented programming (OOP) involves programming
using objects.
 An object represents an entity in the real world that can be
distinctly identified.
 For example, a student, a desk, a circle, a button, and even
a loan can all be viewed as objects.
 An object has a unique identity, state, and behaviors.
 The state of an object consists of a set of data fields (also
known as properties) with their current values.
object‫مجموعة البيانات للي ابغى اخزنهاعن ال‬

 The behavior of an object is defined by a set of methods.


object ‫تصرفات وافعال ال‬methods‫ال‬
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objects

An object has both a state and behavior.


The state defines the object, and the behavior defines
what the object does.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Classes (1 of 2)
Classes are constructs that define objects of the same
type.
A Java class uses variables to define data fields and
methods to define behaviors.
Additionally, a class provides a special type of methods,
known as constructors, which are invoked to construct
objects from the class.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Classes (2 of 2)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


UML: Unified
Modelling Language
UML Class Diagram

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Code in next slide
Example: Defining Classes and Creating
Objects (1 of 2)
Objective: Demonstrate creating objects, accessing data,
and using methods.

TestSimpleCircle
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
[Link]

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Home Practice!
Example: Defining Classes and Creating
Objects (2 of 2)

TV
TestTV
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Constructors (1 of 2)
Constructors are a special kind of methods that are
invoked to construct objects.

Circle() {
}

Circle(double newRadius) {
radius = newRadius;
}

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Constructors (2 of 2)
A constructor with no parameters is referred to as a No-arg
Constructor (No-argument Constructor)
• Constructors must have the same name as the class
itself.
• Constructors do not have a return type—not even void.
• Constructors are invoked using the new operator when
an object is created.
• Constructors play the role of initializing objects.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Creating Objects Using Constructors
new ClassName();

Example:
new Circle();

new Circle(5.0);

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Default Constructor
A class may be defined without constructors.
In this case, a no-arg constructor with an empty body is
implicitly defined in the class.
This constructor, called a default constructor, is provided
automatically only if no constructors are explicitly
defined in the class.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Declaring Object Reference Variables
.‫ قم بتعيني الكائن إلى متغير مرجعي‬،‫لإلشارة إلى كائن‬

To reference an object, assign the object to a reference


variable.
To declare a reference variable, use the syntax:
ClassName objectRefVar;
Example:
Circle myCircle;

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Declaring/Creating Objects in a Single
Step
ClassName objectRefVar = new ClassName();

Example:

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Accessing Object’s Members
• Referencing the object’s data:

[Link]
e.g.,
[Link]
• Invoking the object’s method:

[Link](arguments)
e.g.,
[Link]()
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (1 of 7)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Trace Code (2 of 7)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Trace Code (3 of 7)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Trace Code (4 of 7)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Trace Code (5 of 7)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Trace Code (6 of 7)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Trace Code (7 of 7)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Caution
Recall that you use
[Link](arguments) (e.g., [Link](3, 2.5))

to invoke a method in the Math class.


Can you invoke getArea() using [Link]()?

The answer is no. Most of the methods used before this chapter are
static methods, which are defined using the static keyword.
However, getArea() is non-static. It must be invoked/called from an
object using
[Link](arguments) (e.g.,
[Link]()).

More explanations will be given in the following sections on “Static


Variables, Constants, and Methods.”

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Reference Data Fields
The data fields can be of reference types.
For example, the following Student class contains a
data field name of the String type.

public class Student


{
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has
// default value false
char gender; // c has default value '\u0000’
}

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


The Null Value
If a data field of a reference type does not reference (does
not hold an address of) any object, the data field holds a
special literal value, null.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Default Value for a Data Field
Just like array elements, 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.
However, Java assigns no default value to a local variable
inside a method.
public class ShowDefaultValues {
public static void main(String[] args) {
Student student = new Student();
[Link]("name? " + [Link]);
[Link]("age? " + [Link]);
[Link]("isScienceMajor? " +
[Link]);
[Link]("gender? " + [Link]);
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example
Java assigns no default value to a local variable inside a
method.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Differences Between Variables of Primitive
Data Types and Object Types

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Copying Variables of Primitive Data
Types and Object Types

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Garbage Collection (1 of 2)
 As shown in the previous figure, after the assignment
statement c1 = c2, c1 points to the same object
referenced by c2.
 The object previously referenced by c1 is no longer
referenced.
 This object is known as garbage. Garbage is
automatically collected by JVM.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Garbage Collection (2 of 2)
Tip: If you know that an object is no longer needed, you
can explicitly assign null to a reference variable for the
object.
The JVM will automatically collect the space if the object is
not referenced by any variable.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


The Date Class
Java provides a system-independent encapsulation of date
and time in the [Link] class. You can use
the Date class to create an instance for the current date
and time and use its toString method to return the date
and time as a string.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


The Date Class Example
For example, the following code
[Link] date = new [Link]();
[Link]([Link]());

displays a string like Sun Mar 09 13:50:19 EST 2003.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Already given
in Chapter 3
The Random Class
You have used [Link]() to obtain a random
double value between 0.0 and 1.0 (excluding 1.0). A more
useful random number generator is provided in the
[Link] class.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


The Random Class Example
If two Random objects have the same seed, they will generate identical
sequences of numbers. For example, the following code creates two
Random objects with the same seed 3.
Random random1 = new Random(3);
[Link]("From random1: ");
for (int i = 0; i < 10; i++)
[Link]([Link](1000) + " ");
Random random2 = new Random(3);
[Link]("\nFrom random2: ");
for (int i = 0; i < 10; i++)
[Link]([Link](1000) + " ");

From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Code in next slide

The Point2D Class


Java API has a conveninent Point2D class in the
[Link] package for representing a point in a
two-dimensional plane.

TestPoint2D
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
[Link]

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Instance Variables, and Methods
Instance variables belong to a specific instance.
Instance methods are invoked by an instance of the class.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Static Variables, Constants, and
Methods (1 of 3)

Static variables are shared by all the instances of the class.


Static methods are not tied to a specific object.
Static constants are final variables shared by all the
instances of the class.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Static Variables, Constants, and
Methods (2 of 3)

To declare static variables, constants, and methods, use


the static modifier.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Static Variables, Constants, and
Methods (3 of 3)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Code in next slide
Example of Using Instance and Class
Variables and Method
Objective: Demonstrate the roles of instance and class
variables and their uses. This example adds a class
variable numberOfObjects to track the number of Circle
objects created.

CircleWithStaticMembers

TestCircleWithStaticMembers

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


[Link]

Visit second link in previous


slide, press Compile&Run,
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Visibility Modifiers and Accessor/Mutator
Methods (1 of 3)
By default, the class, variable, or method can be accessed
by any class in the same package.
• Public
The class, data, or method is visible to any class in any
package.
• Private

The data or methods can be accessed only by the


declaring class.
The get and set methods are used to read and modify
private properties.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Visibility Modifiers and Accessor/Mutator
Methods (2 of 3)

The private modifier restricts access to within a class, the


default modifier restricts access to within a package, and
the public modifier enables unrestricted access.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Visibility Modifiers and Accessor/Mutator
Methods (3 of 3)

The default modifier on a class restricts access to within a


package, and the public modifier enables unrestricted
access.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Note
An object cannot access its private members, as shown in
(b). It is Ok, however, if the object is declared in its own
class, as shown in (a).

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Why Data Fields Should Be Private?
To protect data.
To make code easy to maintain.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Code in next slide

Example of Data Field Encapsulation

CircleWithPrivateDataFields

TestCircleWithPrivateDataFields
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
[Link]

Visit second link in previous


slide, press Compile&Run,
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Code in next slide

Passing Objects to Methods (1 of 2)


• Passing by value for primitive type value (the value is
passed to the parameter)
• Passing by value for reference type value (the value is
the reference to (address of) the object)

TestPassObject

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


[Link]

Visit link in previous slide,


press Compile&Run,
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Passing Objects to Methods (2 of 2)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Array of Objects (1 of 3)
Circle[] circleArray = new Circle[10];
An array of objects is actually an array of reference variables.
So invoking circleArray[1].getArea() involves two levels
of referencing as shown in the next figure:
circleArray references the entire array.
circleArray[1] references the second Circle object.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Array of Objects (2 of 3)
Circle[] circleArray = new Circle[10];

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Array of Objects (3 of 3)
Summarizing the areas of the circles

TotalArea

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Immutable Objects and Classes
If the contents of an object cannot be changed once the
object is created, the object is called an immutable object
and its class is called an immutable class.
If you delete the set method in the Circle class in
Listing 8.10, the class would be immutable because radius
is private and cannot be changed without a set method.
A class with all private data fields and without mutators is
not necessarily immutable.
For example, the following class Student has all private
data fields and no mutators, but it is mutable.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Example (2 of 3)
public class Student { public class BirthDate {
private int id; private int year;
private BirthDate birthDate; private int month;
public Student(int ssn, private int day;
int year, int month, int
day) { public BirthDate(int newYear,
id = ssn; int newMonth, int newDay)
birthDate = new {
BirthDate(year, month, day); year = newYear;
} month = newMonth;
day = newDay;
public int getId() { }
return id;
} public void setYear(int
public BirthDate newYear) {
getBirthDate() { year = newYear;
return birthDate; }
} }
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example (3 of 3)
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333,
1970, 5, 3);
BirthDate date = [Link]();
[Link](2010); // Now the student
birth year is changed!
}
}

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


What Class Is Immutable?
For a class to be immutable, it must mark all data fields
private and provide no mutator methods and no accessor
methods that would return a reference to a mutable data
field object.

Accessor/Mutator

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Scope of Variables
• The scope of instance and static variables is the entire
class. They can be declared anywhere inside a class.
• The scope of a local variable starts from its declaration
and continues to the end of the block that contains the
variable. A local variable must be initialized explicitly
before it can be used.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


The this Keyword
• The this keyword is the name of a reference that refers
to an object itself. One common use of the this keyword
is reference a class’s hidden data fields.
• Another common use of the this keyword to enable a
constructor to invoke another constructor of the same
class.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Reference the Hidden Data Fields

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Calling Overloaded Constructor

Copyright © 2024 Pearson Education, Inc. All Rights Reserved


Copyright

This work is protected by United States copyright laws and is


provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved

You might also like