1

Programming II (CS300) Chapter 02: Using Objects

MOUNA KACEM [email protected] Fall 2018 Using Objects 2

u Introduction to Object Oriented Programming Paradigm

u Objects and References

u Memory Management in Java

u Keep in Mind Object-Oriented Programming Paradigm 3

u Object-oriented (OO) design goals:

u Improvement over the procedural/structured programming paradigm

u Robustness

u Adaptability

u Reusability

u Emphasis on data rather than algorithms

u Data and associated operations are unified

u Grouping objects with common attributes, operations and semantics Object-Oriented Programming Paradigm 4

Procedural/Structured Programming Object-Oriented Programming Paradigm Paradigm

u Programs are designed around the u Programs are designed around the data operations

u Algorithmic problem decomposition u Data-centric problem decomposition Object-Oriented Programming Paradigm 5 u Object-Oriented Thinking

u Everything in the world is an object

u Any system consists of a set of interacting objects

u Interactions among the objects inside and outside the system

Flower Tree Student House Object-Oriented Programming Paradigm 6

u Object Oriented Design Principles

Abstraction Encapsulation Modularity Object-Oriented Programming Paradigm 7

u Object u The main “actor” in Object-oriented programming paradigm u Instance of exactly one class u Represents the properties of a single instance of a class u Class u A class represents a Data type (prototype or model) u A class represents a description of the common properties of a set of objects u A class can be viewed as a “recipe” on how to make or generate objects u The class should be defined before creating any instance (object) of that class u Properties u Data attributes u Methods u Sequence of instructions that a class or an object follows to perform a task (functions/capabilities) Objects and References 8 u Object Concept

u An object is an instance of a Class

u An object is an encapsulation of Data

u An object has

u Identity (a unique reference)

u State (also called fields or variables)

u Each object has its own variables

u Behaviors

u All objects instances of the same class share the methods defined by the class Objects and References 9 u Class Concept

u A class is used as a template or pattern to create new objects

u A class defines

u the variables that hold the object’s state

u the methods that describe the object’s behaviors Objects and References 10 Object-Oriented Abstraction Programming

Class

Properties Data (State)

Entity

Methods Operations (Behaviors)

Instantiate Instantiate Instantiate … Object Object1 n

Object2 Objects and References 11

u Example: Class definition and object instantiation

public class Student { private String name; // Student’s name. private double test1, test2, test3; // Grades on three tests.

public double getAverage(){ // compute average test grade // code goes here (method implementation) }

} // end of class Student Objects and References 12 u Object Instantiation (Example) Objects and References 13 u Object Instantiation (Example) Objects and References 14

u Object Instantiation (Example): References illustration

864 Instance1of Student std Instance1 1000 Instance2of Student of Student (@ 864) 1024 std = 864 std1

std1 = 1000 Instance2 3200 of Student 5436 std2 = 1000 (@ 1000) std2 5508 std3 = null X

std3 Objects and References 15 u Object Instantiation (Example) Objects and References 16 u Object Instantiation (Example)

Object no longer accessed Garbage ! Objects and References 17

u There are only eight primitive types in Java u byte, short, int, long, float, double, char, and boolean. u Any other type including String is a reference type

u All variables of a reference type (non-primitive type) are objects and are accessed via a reference u In Java, fields of classes and objects that do not have an explicit initializer and elements of arrays are automatically initialized with the default value for their type u false for boolean, u 0 for all numerical types, u null for all reference types Objects and References 18 u Object Behaviors

u Constructors

u Constructors are invoked only when the object is created

u Constructors initialize the state of an object upon creation

u Accessor Methods

u An accessor method is used to return the value of a private

u Accessor or getter: the method name begins with the prefix “get” Objects and References 19 u Object Behaviors u Accessor Methods u An accessor method is used to return the value of a private field u Accessor or getter: the method name begins with the prefix “get” u Mutator Methods u A is used to set a value of a private field u A mutator method does not have a return type u Mutator or setter: the method name begins with the prefix “set” u Why it is recommended to use Accessors and Mutators to access to a private field? u One of the ways to enforce encapsulation Objects and References 20

u Constructor (Example)

public class Person { // Defined Constructor public Person(String firstName, String lastName, String address) { //Private fields this.firstName = firstName; private String firstName; this.lastName = lastName; private String lastName; this.address = address; private String address; }

// Default Constructor } public Person(){ firstName = " "; // Declare two variables of type Person lastName = " "; Person person1, person2; //references to objects of type Person address = " "; } // Create two Person objects and store their references in person1 and person2 variables Person person1 = new Person(); Person person2 = new Person(“Mouna”, “KACEM”, “Madison”); Objects and References 21

u Accessors and Mutators Examples

//Accessor for firstName //Mutator for firstname public String getFirstName(){ public void setFirstname(String firstname) { return firstName; this.firstname = firstname; } }

//Accessor for lastName //Mutator for address public String getLastName(){ public void setAddress(String address){ return lastName; this.address = address; } } Objects and References 22

u Message Passing

u An Object-Oriented application is a set of cooperating objects that communicate with each other

u In Java, "message passing" is performed by invoking (calling) methods

u A message is sent to an object using the “dot notation”:

u objectReference.methodX();

u objectReference.fieldY;

u When an object receives a message, it looks for the corresponding method (ie. with the same signature) in its class. Then, it invokes and executes that method. Using Objects 23

u Introduction to Object Oriented Programming Paradigm

u Objects and References

u Memory Management in Java

u Keep in Mind Memory Management in Java 24 u What’s Memory Management?

u Memory management is the process of managing the memory space (of the RAM) allocated to a program while it is running

u A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a Java program (i.e. the JVM represents the Java application)

u Managing the memory space used by a JVM includes

u Allocating Java code, called methods and their local variables in the memory

u Allocating new created objects

u Removing unused objects Memory Management in Java 25 u Java Memory Model (1) Code u The Java memory model specifies how the Java Heap Virtual Machine (JVM) uses the computer memory (RAM) (memory Allocation) Static A computer allocates mainly two dynamic areas of Memory memory for a program:

u Stack to store information about method calls Stack u When a piece of code calls a method, information (method call) about the call is placed on the stack.

u When the method returns, that information is popped off the stack console.log()

u Heap contains all objects created by the application main() JVM Memory Management in Java 26

Thread1 Stack Thread2 Stack

Heap

JVM

u Java Memory Model (2)

u Each thread running in the JVM has its own stack (Thread Stack)

u All threads running in the JVM share the heap Memory Management in Java 27 u Java Memory Model (3) u A thread stack contains information about Thread1 Stack Thread2 Stack

u The methods called by a thread to reach method_f() method_A() the current point of execution (call stack) Local variable1 Local variable1 Local variable2 u All local variables for each method being Local variable2 executed Local variable3 method_g() method_B() u Local variables related to one thread are not visible to the all other threads including Local variableX Local variableY u local variables of primitive data types (boolean, char, byte, short, int, long, float, double) Heap u If two threads are executing the exact same code (multi-thread applications), u Each thread will create its own local variables of JVM that code in its own thread stack Memory Management in Java 28 u Java Memory Model (2)

u The heap contains all objects Thread1 Stack Thread2 Stack created in the Java application method_f() method_A() u Including the object version of Local variable1 Local variable1 primitives types (Boolean, Byte, Local variable2 Local variable2 Character, Double, Float, Integer, Local variable3 Long, Short, and Void) method_g() method_B() Local variableX Local variableY

u Objects on the heap are visible Heap Object1 Object4 to all threads Object3

Object2 Object5 JVM Memory Management in Java 29

u Garbage Collection

u Java Garbage Collector is responsible for freeing objects when they are no longer accessed

u Reclaims heap space

u No manual garbage collection in Java

u Fully automatic process which runs periodically and performs the real destruction of the objects Keep in Mind 30

u A reference is a variable that stores the memory address where an object is temporarily stored in the stack or the special reference null.

u An object can be referenced by multiple references

u “==“ operator is used to compare two references

u It returns true if the two references refer to the same object

u “=“ operator makes a reference variable refer to another object

u “.” operator allows the selection of object’s method or access to its fields Keep in Mind 31

u Reference types

u For reference types and arrays, “=“ is a reference assignment rather than an object copy. (It does not make a copy of object values. Instead, it copies addresses)

u For reference types and Strings, “equals” should be used instead of “==“ to test if two objects have identical states u In order to enforce encapsulation, use accessors and mutators to access to an object’s private fields u Garbage collection

u Automatic reclaiming of unreferenced memory