[go: up one dir, main page]

0% found this document useful (0 votes)
5 views68 pages

F CSC125 - Ch9

This document provides an overview of object-oriented programming concepts, focusing on defining classes and objects, constructors, and encapsulation. It includes activities for creating a Circle class and emphasizes the importance of data field encapsulation and immutability. Additionally, it discusses visibility modifiers, static variables, and the use of the 'this' reference in Java programming.

Uploaded by

2k7kdhqhym
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)
5 views68 pages

F CSC125 - Ch9

This document provides an overview of object-oriented programming concepts, focusing on defining classes and objects, constructors, and encapsulation. It includes activities for creating a Circle class and emphasizes the importance of data field encapsulation and immutability. Additionally, it discusses visibility modifiers, static variables, and the use of the 'this' reference in Java programming.

Uploaded by

2k7kdhqhym
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/ 68

CSC 125

Object Oriented
Programming

Chapter 9

Dr Khulood Alkhateeb
Objects and
Classes
Introduction

● Object-oriented programming enables you to develop large-scale software


and GUIs effectively
● It's a technology for developing reusable software
Defining classes for objects

● A class defines the properties and behaviors for objects


● An object has a unique identity, state, and behavior:
○ The state of an object (also known as its properties or attributes) is represented by data
fields with their current values.
○ 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

● Objects are defined by a class


Defining classes for objects
UML class diagram

● A class is a template, blueprint, or contract that defines what


an object’s data fields and methods will be.

● Think of a factory creating TVs,


○ one blueprint (plan) creates many physical TVs:

○ A TV will have a set of attributes or properties eg, is it on/off, volume level,


current channel

○ A TV will have a set of behaviors or actions that can be done:

■ turnOn turnOff

■ Set channel

■ Set volume

■ Etc
Activity

Create a circle class in a project named TestCircle:

● First create a UML diagram for the circle class then write the code
Activity

If you run the project nothing happens -> you need to create the objects

For that you need to use main in your main class(the class that contains main)

Creates a circle
object that uses
the default value
of radius set
inside of the
Circle Class
Activity

Now create a new circle object with a different value for radius:

An object’s data fields and


methods can be accessed
through the dot (.) operator
via the object’s reference
variable.
Defining classes for objects

● An object is an instance of a class. Creating an instance is referred to as


instantiation.
● a class provides methods of a special type, known as constructors which
are invoked to create a new object. designed to perform initialization
actions
● ‘new’ operator is used to create an object from the constructor:
● These two objects (referenced by c1, and c2) have different data but the
same methods
● represent class object with a UML notation for objects:
Defining classes for objects

● You can put the two classes into one file


● but only one class in the file can be a public class
● the public class must have the same name as the file name
● Each class in the source code is compiled into a .class file.
● Thus even though we have 1 project file, when compiled we will end up with
two .class files
The Constructor

● A constructor is invoked to create an object using the new operator.


● It's a special kind of method with the following characteristics:
○ must have the same name as the class itself
○ does not have a return type—not even void
○ Is invoked using the new operator when an object is created
○ plays the role of initializing objects
Activity

● Now add the constructor:


The Constructor

● A class normally provides a constructor without arguments (e.g., Circle()).


Such a constructor is referred to as a no-arg or no-argument constructor

● constructors can be overloaded (just like what we did with max method)
Activity

Overloaded constructor to set the value of


radius:

● In the previous circle class: overload the


constructor to be able to pass a value to
set the radius through the constructor
Activity
The Constructor

● a common mistake to put the void keyword in front of a constructor.

● This makes Circle() a method not a constructor


● A class may be defined without constructors. In this case, a public 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
Object Access via Reference Variables

● Newly created objects are allocated in the memory. They can be accessed
via reference variables

variable myCircle
can reference a
Circle object
Object Access via Reference Variables

● creates an object and assigns its reference to myCircle


Object Access via Reference Variables

● You can write a single statement that combines the declaration of an


object reference variable, the creation of an object, and the assigning of an
object reference to the variable
Object Access via Reference Variables

● Example:
Accessing an Object’s Data and Methods

● An object’s data fields and methods can be accessed through the dot (.)
operator via the object’s reference variable
● dot operator = object member access operator
● objectRefVar.dataField:
○ references a data field in the object and is referred to as an instance variable
● objectRefVar.method(arguments):
○ invokes a method on the object and is referred to as an instance method
● The object on which an instance method is invoked is called a calling
object
Accessing an Object’s Data and Methods

Can you invoke getArea() using Circle. getArea()?

The answer is no
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
● 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
● Note: Java assigns no default value to a local variable inside a regular
method
Activity

Create a student class with fields name, age, gander, isCSMajor.

Then create a Student object without assigning values and print them, see
what you get.
Differences between Variables of Primitive Types
and Reference Types

● Every variable represents a memory location that holds a value.


● When you declare a variable, you are telling the compiler what type of value
the variable can hold.
○ For a variable of a primitive type, the value is of the primitive type.
○ For a variable of a reference type, the value is a reference to where an object is located.
Differences between Variables of Primitive Types
and Reference Types

● When you assign one variable to another:


○ For a variable of a primitive type, the real value of one variable is assigned to the other
variable.
Differences between Variables of Primitive Types
and Reference Types

● When you assign one variable to another:


○ For a variable of a reference type, the reference of one variable is assigned to the other
variable.

What
happens to
this?
Differences between Variables of Primitive Types
and Reference Types

● Note: 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 using its garbage collection.
TestCircle example
Static Variables, Constants, And Methods

● A static variable is shared by all objects of the class.


● To create a static variable you add ‘static’ keyword in its declaration.
Activity

● Modify the Circle class and add a static


variable numberOfObjects to count the
number of circle objects created
Static Variables, Constants, And Methods

● A static variable is shared by all objects of the class.


● An instance variable is tied to a specific instance of the class; it is not
shared among objects of the same class
● If you want all the instances of a class to share data, use static variables,
also known as class variables
● Static variables store values for the variables in a common memory
location
● if one object changes the value of a static variable, all objects of the same
class are affected
● Java supports static methods as well as static variables.
● Static methods can be called without creating an instance of the class
● Static variables can be accessed without creating objects.
Static Variables, Constants, And Methods

● The relationship between static and instance members:


○ A static method cannot access instance members (i.e., instance data fields and methods)
of the class
Visibility Modifiers

● The keyword public is a visibility modifier for classes, methods, and data fields
● It denotes that they can be accessed from any other classes.
● Visibility modifiers can be used to specify the visibility of a class and its
members.
● A visibility modifier specifies how data fields and methods in a class can be
accessed from outside the class.
● If no visibility modifier is used, then by default the classes, methods, and data
fields are accessible by any class in the same package -> aka package-private
or package-access
● If a class is defined without the package statement, it is said to be placed in the
default package
Visibility Modifiers

● Java also provides the private modifier for class members:


○ makes methods and data fields accessible only from within its own class
● Example:
Visibility Modifiers

● If a class is not defined as public, it can be accessed only within the same
package
Visibility Modifiers

● There is no restriction on accessing data fields and methods from inside


the class.
Visibility Modifiers

Note:

● if you want to prohibit the user from creating an instance of a class, use a
private constructor.
● Example:
○ To prevent the user from creating objects from the Math class, the constructor in
java.lang.Math is defined as follows
Data Field Encapsulation

● Is it okay that the data fields radius and numberOfObjects in the Circle
class can be modified directly?
● Not good practice. Why?
○ Data may be tampered with. Example: numberOfObjects is to count the number of objects
created, but it may be mistakenly set to an arbitrary value that is not the real number of
objects created.
○ The class becomes difficult to maintain and vulnerable to bugs. Example: Suppose that
you want to ensure that the radius is non-negative. how when it can be modified directly
(e.g., c1.radius = –5)
● Solution:
○ Data Field Encapsulation
Data Field Encapsulation

● Encapsulating is making data fields private.


● This protects data and makes the class easy to maintain
● How?
○ declare the data fields private, using the private modifier
Data Field Encapsulation

● Now the question becomes:


○ how can we now change those private values?
● Solution:
○ Adding getter (aka accessor) methods and
○ Setter (aka mutator) methods
Data Field Encapsulation

● Getter (aka accessor) methods:

● If the return Type is boolean:


Data Field Encapsulation

● setter (aka mutator) methods


Activity

Change the Circle class create before to make the data-field private and create
their associated accessor and mutator methods
Activity
Data Field Encapsulation

● This makes the class easy to maintain.


Data Field Encapsulation

● What if main was inside Circle class, will main be able to access a private
member? Try it out
Passing objects to methods

● Passing an object to a method is to pass the reference of the object.


● Same like arrays before we called it passing a reference (pass-by-sharing)
Activity

Add a method to the TestCircle class to print information about a created Circle
object. For example, print its radius and its area
Immutable objects and classes

● You can create an object whose contents cannot be changed once the
object has been created.
● We call such an object as immutable object and its class as immutable
class
● If a class is immutable, then all its data fields must be private and it cannot
contain public setter methods for any data fields
Activity

● deleted the setter method in the Circle class


● the class would be immutable because radius is private and cannot be
changed without a setter method
Immutable objects and classes

For a class to be immutable, it must meet the following requirements:

● All data fields must be private


● There can’t be any mutator methods for data fields
● No accessor methods can return a reference to a data field that is mutable
Immutable objects and classes

Is this immutable?

No, 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
The scope of Variables

● Instance and static variables in a class are referred to as the class’s


variables or data fields.
● 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 scope of Variables

● 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
The scope of Variables

● You can declare a class’s variable only


once, but you can declare the same
variable name in a method many
times in different non-nesting blocks.
● 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. x=1

y=0
The this reference

● the this reference is needed to reference a data field hidden by a method or


constructor parameter, or to invoke an overloaded constructor
The this reference

● The keyword this refers to the object itself.


● use the this keyword to reference the object’s instance members

(a) uses this to reference the object’s radius and invokes its getArea() method explicitly, often not needed and
often omitted to make the code shorter
The this reference

Using this to Reference Data Fields

● It is a good practice to use the data field as the parameter name in a setter
method or a constructor to make the code easy to read and to avoid
creating unnecessary names

The data field


radius is hidden
by the
parameter
radius in the
The this reference

● A hidden static variable can be accessed simply by using the


ClassName.staticVariable reference
The this reference

Using this to Invoke a Constructor:

● It can also be used inside a constructor to invoke another constructor of


the same class

Java requires that the


this(arg-list) statement
appear first in the
constructor before any
other executable
statements
Extras

● You can separate the Circle class from the main class TestCircle. If you
want to put the class in a separate file you need The constructor and
methods in the class to be defined public so they can be accessed from
other classes.

● you can combine the two classes in the preceding TestCircle example into
one:
○ Put the main in the circle class itself
Activity

Create a circles project with main


inside of Circle class
Questions?
References

Liang. Introduction to Java Programming: Brief Version, 11th edition. Pearson,


2017. ISBN: 978-0134611037.

You might also like