Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 74

Topic 1

Introduction to Object Orientation


Learning Objectives
• At the end of this chapter, you will be able to:
– Describe classes and objects in OOP
– Analyze a problem using object-oriented analysis.
– Construct a simple object-oriented program
Subtopics
1.1 Object-oriented Programming Concepts
Objects
Classes
1.2 Constructors
1.3 Constructing Objects Using Constructors
1.4 Accessing Objects via Reference Variables
1.5 Visibility Modifiers
1.6 Class Abstraction and Encapsulation
1.7 Array of Objects
1.8 Passing Objects to Methods
1.1 Object-oriented Programming Concepts
Objects
• Object-oriented programming (OOP) involves programming using objects.
• An object represents or an abstraction of some entity in the real world that
can be distinctly identified.
– For example, a student, a desk, a circle, a button, a cow, a car, a loan, and etc.
• An object may be physical, like a radio, or intangible, like a song.
• Just as a noun is a person, place, or thing; so is an object
• An object has a
– Unique identity
– State or characteristics or attributes, and
– Action or behavior.
• Specifically, an object is an entity that consists of:
– A set of data fields (also known as properties or attributes) with their current values.
– A set of methods that use or manipulate the data (the behavior).
Objects – Example 1
Circle Object 1 Circle Object 2 Circle Object 3
Data fields: Data fields: Data fields:
radius is 10 radius is 25 radius is 125
Methods: Methods: Methods:
getArea() getArea() getArea()
getPerimeter() getPerimeter() getPerimeter()

An object has both a state and behavior. The


state defines the object, and the behavior
defines what the object does.
Classes
• Objects of the same type are defined using a common
class
• Class is a template, blueprint or contract, from which
objects of the same type are created (defines what an
object’s data fields and methods will be)
• An object is an instance of a class
• We can create many instances of a class
• Creating an instance is referred to as instantiation
• The term object and instance are often interchangeable
Classes (cont..)
Class Name:
Circle Class template
Data fields:
radius
Methods:
getArea()
getPerimeter()

Circle Object 3
Data fields:
radius is 125
Methods:
getArea()
getPerimeter()
Objects – Example 2
• A remote control unit is an object.
• A remote control object has three attributes:
– The current channel, an integer,
– The volume level, an integer, and
– The current state of the TV, on or off, true or false

• Along with five behaviors or methods:


– Raise the volume by one unit,
– Lower the volume by one unit,
– Increase the channel number by one,
– Decrease the channel number by one, and
– Switch the TV on or off.
Objects – Example 2 (Cont.)
Three different remote objects, each with
a unique attribute values (data) but all
sharing the same methods or behaviors.
Objects – Example 2 (Cont.)
The remote control unit exemplifies encapsulation.
 Encapsulation is defined as the language feature of
packaging attributes and behaviors into a single unit.
 Data and methods comprise a single entity.
 Each remote control object encapsulates data and methods,
attributes and behaviors.
 An individual remote unit, an object, stores its own
attributes – channel number, volume level, power state –
and has the functionality to change those attributes.
Objects – Exercise
• A rectangle is an object.
• The attributes of a rectangle might be length
and width, two floating point numbers; the
methods compute and return area and
perimeter.
• Each rectangle has its own set of attributes; all
share the same behaviors
• Draw three rectangle objects
Classes (cont..)
• A Java class uses
– variables to define data fields and
– methods to define actions.
• Additionally, a class provides a special type of
methods, known as constructors, which are invoked
to create new objects from the class.
• A constructor can perform any action, but
constructors are designed to perform initializing
action, such as initializing the data fields of objects
class Circle {
/** The radius of this circle */
Classes (cont..)
double radius = 1.0;
Data field
/** Construct a circle object */
Circle() {
}

/** Construct a circle object */ Constructors


Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() {
return radius * radius * Math.PI;
}

/** Return the perimeter of this


circle */
double getPerimeter(){
return 2 * radius * Math. PI; Method
}

/** Set a new radius for this circle */


void setRadius(double newRadius){
radius = newRadius;
}
}
Unified Modelling Language (UML) Class
Diagram
Circle Class name
radius : double Data fields
Circle()
Circle(newRadius : double)
getArea() : double Constructors and
getPerimeter(): double
setRadius(newRadius: double) : void Methods

Notation:
In data field dataFieldName: dataFieldType

constructor ClassName(parameterName: parameterType)

method methodName(parameterName: parameterType) : returnType


UML notation for objects

Circle1: Circle Circle2: Circle Circle3: Circle


radius = 1 radius = 25 radius = 125
1.2 Constructors
• Constructors are a special kind of methods that are
invoked to construct a new object, initialize it with the
construction parameters, and return a reference to the
constructed object.
• Example:
Circle() {
}

Circle(double newRadius) {
radius = newRadius;
}
Constructors (Cont.)
• Three peculiarities
– 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.
• A constructor with no parameters is referred to as a
no-arg constructor.
• Constructors can be overloaded(multiple constructors
can have the same name but different signature)
Constructors (Cont.)
• A class may be declared without constructors.
• In this case, a no-arg constructor with an
empty body is implicitly declared in the class.
• This constructor, called a default constructor,
is provided automatically only if no
constructors are explicitly declared in the
class.
Classes – Exercise
Rectangle Class

• A Rectangle class might specify that every Rectangle object consists of two variables
of type double:
– double length, and
– double width,

• Every Rectangle object comes equipped with two methods:


– double area(), //returns the area, length x width,
– double perimeter(), //returns the perimeter, 2(length + width).

• Individual Rectangle objects may differ in dimension but all Rectangle objects share
the same methods

• Question:
– Draw a UML class diagram of rectangle class
– Create a rectangle class
1.3 Constructing Objects Using
Constructors
• Creating Objects Using Constructors
Syntax:
new ClassName(); // default constructor
new ClassName(parameter);

Example:
new Circle();
new Circle(25);
1.4 Accessing Objects via Reference Variables

• Newly created objects are allocated in the memory,


accessed via reference variables
• To reference an object, assign the object to a
reference variable.
• To declare a reference variable, use the syntax:
ClassName objectRefVar; A class is a reference type, which means
a variable of the class type can reference
an instance of the class

Example:
Circle myCircle;
The variable myCircle can reference a Circle object
Declaring/Creating Objects in a Single Step
Syntax:
ClassName objectRefVar = new ClassName();

Example:
Assign object reference

Circle myCircle = new Circle();

Create an object
Accessing Objects data and Methods
• Data field can be accessed and its methods invoked using the
dot operator (.)
– known as object member access operator.

• Referencing the object’s data field:


– objectRefVar.data
– e.g., myCircle.radius

• Invoking the object’s method:


– objectRefVar.methodName(arguments)
– e.g., myCircle.getArea()
Instance Variables, and Instance Methods

• Instance variables belong to a specific


instance.
• Instance methods are invoked by an instance
of the class.
• The object on which an instance method is
invoked is called a calling object
A Simple Circle Class
• Objective:
Demonstrate creating objects, accessing data,
and using methods
class Circle {
double radius;
Circle( ) {
radius = 1.0;
}
Circle(double newRadius) {
radius = newRadius;
}
double getArea( ) {
return radius * radius * Math.PI;
}
}
public class TestCircle1 {
public static void main(String[] args) {
Circle myCircle = new Circle(5.0);
System.out.println("The area of the circle of radius " +
myCircle.radius + " is " +
myCircle.getArea());
Circle yourCircle = new Circle();
System.out.println("The area of the circle of radius "+
yourCircle.radius + " is " +
yourCircle.getArea());
yourCircle.radius = 100;
System.out.println("The area of the circle of radius " +
yourCircle.radius + " is " +
yourCircle.getArea());
}
}
Trace Code
Declare myCircle

Circle myCircle = new Circle(5.0); no value


myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100;
Trace Code, cont.

Circle myCircle = new Circle(5.0); no value


myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle


radius: 5.0

Create a Circle
Trace Code, cont.

Circle myCircle = new Circle(5.0); myCircle reference value

Circle yourCircle = new Circle();

yourCircle.radius = 100;

: Circle
Assign object radius: 5.0
reference to myCircle
Trace Code, cont.
myCircle reference value

Circle myCircle = new Circle(5.0);


: Circle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle.radius = 100;

yourCircle no value

Declare yourCircle
Trace Code, cont.
myCircle reference value

Circle myCircle = new Circle(5.0);


: Circle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle.radius = 100;

yourCircle no value

: Circle
radius: 1.0
Create a new
Circle object
Trace Code, cont.
myCircle reference value

Circle myCircle = new Circle(5.0);


: Circle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle.radius = 100;

yourCircle reference value

Assign object
: Circle
reference to
yourCircle radius: 1.0
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle


radius: 5.0

yourCircle reference value

: Circle
Change radius in radius: 100
yourCircle
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'
}
The null Value
• If a data field of a reference type does not
reference any object, the data field holds a
special literal value, null.
Default Value for a Data Field
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 Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " +
student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
Differences between Variables of
Primitive Data Types and Object Types
Copying Variables of Primitive Data Types
and Object Types
Garbage Collection
• 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 Java Virtual Machine
(JVM).
• 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.
1.5 Static Variables, Constants, and Methods

• Static variables are shared by all the instances of


the class.
• Static methods are not tied to a specific object
(cannot access instance member, i.e., instance
data fields and methods of the class).
• Static constants are final variables shared by all
the instances of the class.
• To declare static variables, constants, and
methods, use the static modifier.
Example
UML notation:
Underline: static variable or methods
memory

circle1: Circle
Circle 1 radius
radius = 1
radius: double numberOfObjects = 1
numberOfObjects: int
getNumberOfObjects(): int 1 numberOfObjects
getArea(): double

After one Circle objects was created


Example
UML notation:
Underline: static variable or methods
memory

circle1: Circle
Circle 1 radius
radius = 1
radius: double numberOfObjects = 2
numberOfObjects: int
getNumberOfObjects(): int 2 numberOfObjects
getArea(): double
circle2: Circle
5 radius
radius = 5
numberOfObjects = 2

After two Circle objects were created


Example
To declare a static variable or method in Java,
use the modifier static

Eg
static int numberOfObjects;

static int getNumberOfObjects(){


return numberOfObjects;
}
class Circle2 {
double radius;
static int numberOfObjects = 0;

Circle2( ) {
radius = 1.0
numberOfObjects++; }

Circle2(double newRadius) {
radius = newRadius;
numberOfObjects++; }

double getArea( ) {
return radius * radius * Math.PI; }

static int getNumberOfObjects() {


return numberOfObjects; }
}
1.5 Visibility Modifiers
• Visibility modifiers can be used to specify the visibility of a
class and its members
• 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.
• If no visibility modifier is used, then by default the class,
variable, or method can be accessed by any class in the same
package.
• The get and set methods are used to read and modify private
properties.
package p1; package p2;
public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() { cannot access o.z; cannot access o.z;
}
void m2() { can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
private void m3() { cannot invoke o.m3(); cannot invoke o.m3();
} } }
} } }

package p1; package p2;


class C1 { public class C2 { public class C3 {
... can access C1 cannot access C1;
} } can access C2;
}
1.6 Class Abstraction and Encapsulation

• Class abstraction means to separate class implementation from the use


of the class.
• The creator of the class provides a description of the class and let the
user know how the class can be used.
• The user of the class does not need to know how the class is
implemented.
• The detail of implementation is encapsulated and hidden from the user.
Why Data Fields Should Be private?
• To protect data.
• To make class easy to maintain.
Why Data Fields Should Be private?
• Example:
– Data field radius and numberOfObjects in the Circle2 class can be
modified directly (e.g. myCircle.radius = 5).
• This is not a good practice:
– Data may be tampered. For example, numberOfObjects is to
count the number of objects created, but it may be set to an
arbitrary value (e.g. Circle2.numberOfObjects = 10).
– It makes the class difficult to maintain and vulnerable to bugs.
Suppose you want to modify the Circle2 class to ensure that the
radius is non-negative after other programs have already used
the class. You have to change not only the Circle2 class, but also
the programs that use the Circle2 class.
Why Data Fields Should Be private?
• Data field encapsulation: declare the data field as
private to prevent direct modification of properties
• Provide a get method to return the value of the
data field. (getter/accessor)
– Accessor method does not change the state of its
implicit parameter.
• Provide a set method to enable a private data field
to be updated (setter/mutator)
– Mutator method changes the state
getter and setter methods
• Signature for getter method
public returnType getPropertyName()

• Signature for setter method


public void setPropertyName(datatype propertyValue)
Example of Data Field Encapsulation
public class Circle3 {
private double radius = 1;
private static int numberOfObjects = 0;

public Circle3( ) {
numberOfObjects++; }

public Circle2(double newRadius) {


radius = newRadius;
numberOfObjects++; }

public void setRadius(double newRadius ) {


radius = (newRadius >= 0) ? newRadius : 0; }

public static int getNumberOfObjects() {


return numberOfObjects; }

public double getArea() {


return radius * radius * Math.PI
}
}
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 the
preceding example, 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 Student class has all private
data fields and no mutators, but it is mutable.
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.
1.7 Array of Objects
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 figure below.
• circleArray references to the entire array.
• circleArray[1] references to a Circle object.
public class TotalArea {
public static void main(String[] args) {
Circle3[] circleArray;
circleArray = createCircleArray();
printCircleArray(circleArray);
}

public static Circle3[] createCircleArray() {


Circle3[] circleArray = new Circle3[10];
for (int i = 0; i < circleArray.length; i++)
circleArray[i] = new Circle3(Math.random() * 100);
return circleArray;
}
public static printCircleArray(Circle3[] circleArray) {
System.out.println ("Radius\t\t\t\t" + "Area");
for (int i = 0; i < circleArray.length; i++) {
System.out.println(circleArray[i].getRadius() + "\t\t" +
circleArray[i].getArea() + ‘\n’);
}
System.out.println("-----------------");
System.out.println("The total areas of circles is \t" +
sum(circleArray);
}

public static double sum(Circle3[] circleArray) {


double sum = 0;
for (int i = 0; i < circleArray.length; i++)
sum += circleArray[i].getArea();
return sum;
}
1.8 Passing Objects to Methods
• 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 the object)
public class Test {
public static void main(String[] args) {
//Circle is defined previously
Circle myCircle = new Circle(5.0);
printCircle(myCircle);
}

public static void printCircle(Circle c){


System.out.println(“The area of the circle of radius “ +
c.getRadius() + “ is “ + c. getArea());
}
}
public class TestPassObject {
public static void main(String[] args) {
//Circle is defined previously
Circle myCircle = new Circle(1);
int n = 5;
printArea(myCircle,n);
}

public static void printCircle(Circle c, int times){


System.out.println(“Radius \t\tArea”);
while (times >= 1) {
System.out.println(c.getRadius() + “\t\t” + c. getArea());
c.setRadius(c.getRadius + 1);
times --;
}
}
}
Scope of Variables: in the context of a class

• 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.
• The exception is when a data field is initialized
based on reference to another data field.
Scope of Variables
public class Circle { public class Foo {
public double find getArea() { private i;
return radius * radius * Math.PI; private int j = i + 1;
} }

private double radius = 1;


} i has to be declared before j
because j’s initial value depends
on i

Variable radius and method getArea can be


declared in any oder
Local variable takes precedence
and the class’s variable with the
same name is hidden
Keyword this
• The keyword this is the name of a reference
that an object can use to refers to itself
– Use it to reference the object’s instance members
Using this to reference data fields
private double radius;

public void setRadius(double radius){


this.radius = radius;
}
For a hidden static variable can be accessed simply by
using ClassName.staticVariable.

public class F{
private static double k = 0;

public static void setK(double k){


F.k = k;
}
Using this to invoke a constructor
• Keyword this can be used to invoke another
constructor of the same name
Public class Circle{
private double radius;

public Circle(double radius){


this.radius = radius;
}

public Circle(){
this(1.0);
}
}
Summary
• The main thing you do to write class definition for the
various problems that will make up the program.
• A class definition encapsulates its object’s data and behavior.
• Once a class has been defined, it serves as a template, or
blueprint, for creating individual objects or instance of the
class.
• A class definition contains two types of elements: variable
and methods.
• Variable – to store the objects information
• Method – to process the information
• To design an object you need to answer five
basic questions:
– What role will the object perform in the program?
– What data of information will it need?
– What actions will it take?
– What interface will it present to other objects?
– What information will it hide from other objects?
Terima Kasih | Thank You

You might also like