1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Spring 2018
Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management in Java Practice Example (ArrayList) Eclipse Debugger Overview Keep in Mind
Object-Oriented Programming Paradigm 3 Object-oriented (OO) design goals: Improvement over the procedural/structured programming paradigm Robustness Adaptability Reusability Emphasis on data rather than algorithms Procedural abstraction is complemented by data abstraction Data and associated operations are unified Grouping objects with common attributes, operations and semantics
Object-Oriented Programming Paradigm 4 Procedural/Structured Programming Paradigm Programs are designed around the operations Object-Oriented Programming Paradigm Programs are designed around the data Algorithmic problem decomposition Data-centric problem decomposition
Object-Oriented Programming Paradigm 5 Object-Oriented Thinking Everything in the world is an object Any system consists of a set of interacting objects Interactions among the objects inside and outside the system Flower Tree Student House
Object-Oriented Programming Paradigm 6 Object Oriented Design Principles Abstraction Encapsulation Modularity
Object-Oriented Programming Paradigm 7 Object The main actor in Object-oriented programming paradigm Instance of exactly one class Represents the properties of a single instance of a class Class A class represents a Data type (prototype or model) A class represents a description of the common properties of a set of objects A class can be viewed as a recipe on how to make or generate objects The class should be defined before creating any instance (object) of that class Properties Data attributes Methods Sequence of instructions that a class or an object follows to perform a task (functions/capabilities)
Objects and References 8 Object Concept An object is an instance of a Class An object is an encapsulation of Data An object has Identity (a unique reference) State (also called fields or variables) Each object has its own variables Behaviors All objects instances of the same class share the methods defined by the class
Objects and References 9 Class Concept A class is used as a template or pattern to create new objects A class defines the variables that hold the object s state the methods that describe the object s behaviors
Objects and References Entity Abstraction Properties Operations Object-Oriented Programming Class Data (State) Methods (Behaviors) 10 Instantiate Instantiate Object 1 Instantiate Object n Object2
Objects and References 11 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 Object Instantiation (Example)
Objects and References 13 Object Instantiation (Example)
Objects and References 14 Object Instantiation (Example): References illustration 864 Instance1of Student 1000 1024 Instance2of Student std = 864 std std1 Instance1 of Student (@ 864) 3200 std1 = 1000 Instance2 of Student 5436 std2 = 1000 std2 (@ 1000) 5508 std3 = null X std3
Objects and References 15 Object Instantiation (Example)
Objects and References 16 Object Instantiation (Example) Object no longer accessed Garbage!
Objects and References 17 Object Behaviors Constructors Constructors are invoked only when the object is created Constructors initialize the state of an object upon creation Accessor Methods An accessor method is used to return the value of a private field Accessor or getter: the method name begins with the prefix get Mutator Methods A mutator method is used to set a value of a private field A mutator method does not have a return type Mutator or setter: the method name begins with the prefix set Why it is recommended to use Accessors and Mutators to access to a private field? One of the ways to enforce encapsulation
Objects and References 18 Constructor (Example) public class Person { //Private fields private String firstname; private String lastname; private String address; // Default Constructor public Person(){ firstname = " "; lastname = " "; address = " "; } // Defined Constructor public Person(String firstname, String lastname, String address) { this.firstname = firstname; this.lastname = lastname; this.address = address; } } // Declare two variables of type Person Person person1, person2; //references to objects of type Person // 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 19 Accessors and Mutators Examples //Accessor for firstname public String getfirstname(){ return firstname; } //Accessor for lastname public String getlastname(){ return lastname; } //Mutator for firstname public void setfirstname(string firstname) { this.firstname = firstname; } //Mutator for address public void setaddress(string address){ this.address = address; }
Objects and References 20 Message Passing An Object-Oriented application is a set of cooperating objects that communicate with each other In Java, "message passing" is performed by invoking (calling) methods A message is sent to an object using the dot notation : objectreference.methodx(); objectreference.fieldy; 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 21 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management in Java Practice Example (ArrayList) Eclipse Debugger Overview Keep in Mind
Memory Management in Java 22 What s Memory Management? Memory management is the process of managing the memory space (of the RAM) allocated to a program while it is running 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) Managing the memory space used by a JVM includes Allocating Java code, called methods and their local variables in the memory Allocating new created objects Removing unused objects
Memory Management in Java 23 Java Memory Model (1) The Java memory model specifies how the Java Virtual Machine (JVM) uses the computer memory (RAM) A computer allocates mainly two dynamic areas of memory for a program: Stack to store information about method calls When a piece of code calls a method, information about the call is placed on the stack. When the method returns, that information is popped off the stack Heap contains all objects created by the application Heap (memory Allocation) Code Static Memory Stack (method call) console.log() main() JVM
Memory Management in Java 24 Thread1 Stack Thread2 Stack Heap Java Memory Model (2) JVM Each thread running in the JVM has its own stack (Thread Stack) All threads running in the JVM share the heap
Memory Management in Java 25 Java Memory Model (3) A thread stack contains information about The methods called by a thread to reach the current point of execution (call stack) All local variables for each method being executed Local variables related to one thread are not visible to the all other threads including local variables of primitive data types (boolean, char, byte, short, int, long, float, double) If two threads are executing the exact same code (multi-thread applications), Each thread will create its own local variables of that code in its own thread stack Thread1 Stack Thread2 Stack method_f() method_a() Local variable1 Local variable1 Local variable2 Local variable2 Local variable3 method_g() method_b() Local variablex Local variabley Heap JVM
Memory Management in Java 26 Java Memory Model (2) The heap contains all objects created in the Java application Including the object version of primitives types (Boolean, Byte, Character, Double, Float, Integer, Long, Short, and Void) Thread1 Stack method_f() Local variable1 Local variable2 method_g() Local variablex Thread2 Stack method_a() Local variable1 Local variable2 Local variable3 method_b() Local variabley Objects on the heap are visible to all threads Object1 Heap Object3 Object4 Object2 Object5 JVM
Memory Management in Java 27 Garbage Collection Java Garbage Collector is responsible for freeing objects when they are no longer accessed Reclaims heap space No manual garbage collection in Java Fully automatic process which runs periodically and performs the real destruction of the objects
Using Objects 28 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management in Java Practice Example (ArrayList) Eclipse Debugger Overview Keep in Mind
Practice Example1 29 Java ArrayList Class uses a dynamic array for storing a set of elements inherits AbstractList class and implements List interface Main Properties Java ArrayList class can contain duplicate elements Java ArrayList class maintains insertion order Java ArrayList allows random access The dynamic array works at the index basis Iterable extends Collection extends List implements AbstractList extends ArrayList
Practice Example1 (Java ArrayList Class) 30 Constructors ArrayList list1 = new ArrayList(); //creating an empty ArrayList ArrayList<String> list2 = new ArrayList<String>(); //creating an empty ArrayList of elements of type String the type of elements is specified in angular braces ArrayList list2 is forced to have only specified type of objects in it (here String). Adding another type of object, results in a compile time error ArrayList(Collection c) build an array list that is initialized with the elements of the collection c. ArrayList(int capacity) build an array list that has the specified initial capacity.
Practice Example1 (Java ArrayList Class) 31 Main Methods (1) void add(int index, Object element) insert the specified element at the specified position index in a list. boolean addall(collection c) append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. void clear() remove all of the elements from this list. int lastindexof(object o) return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Practice Example1 (Java ArrayList Class) 32 Main Methods(2) Object[] toarray() used to return an array containing all of the elements in this list in the correct order. Object[] toarray(object[] a) used to return an array containing all of the elements in this list in the correct order. boolean add(object o) used to append the specified element to the end of a list. boolean addall(int index, Collection c) used to insert all of the elements in the specified collection into this list, starting at the specified position.
Practice Example1 (Java ArrayList Class) 33 Main Methods (3) Object clone() used to return a shallow copy of an ArrayList. int indexof(object o) used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. void trimtosize() used to trim the capacity of this ArrayList instance to be the list's current size.
Practice Example2 (Java Scanner Class) 34 Scanner Class in Java.util package import java.util.scanner; // This will import just the Scanner class import java.util.*; // This will import the entire java.util package Constructors Scanner s = new Scanner (System.in); // System.in is an InputStream object: Reading from the keyboard Scanner infile = new Scanner (new FileReader("myFile")); // takes a FileReader object as a parameter: Reading from a file If the file "myfile" is not found, a FileNotFoundException is thrown
Practice Example2 (Java Scanner Class) 35 The Scanner looks for tokens in the input and allows the user to read values of various types A token is a series of characters that usually ends with a whitespace Java whitespace: a blank, a tab character, a carriage return, a line break, or the end of the file Scanner Methods nextint() returns the next token as an integer nextfloat() returns the next token as a float nextdouble() returns the next token as a double nextlong() returns the next token as a long nextshort() returns the next token as a short nextboolean() returns the next token as a boolean If the type of the next token does not match the expected returned type, an InputMismatchException is thrown.
Practice Example2 (Java Scanner Class) 36 The Scanner looks for tokens in the input and allows the user to read values of various types A token is a series of characters that usually ends with a whitespace Java whitespace: a blank, a tab character, a carriage return, a line break, or the end of the file Scanner Methods next() returns the next complete token (single word) as a String If no token exists, NoSuchElementException is thrown nextline() returns the rest of the current line (i.e. returns a line of Strings), excluding any line separator at the end
Eclipse Debugger Overview 37 Eclipse includes its own Java Debugger to control the execution of a program. Starting the Debugger To debug your code, you run it in debug mode. Right-click on the Java file, then select Debug As -> Java Application (instead of Run As -> Java Application)
Eclipse Debugger Overview 38 Setting breakpoints A line breakpoint To create one, double-click in the margin next to a line of code. Double-click the icon to remove it. A method breakpoint stops when the debugger enters or exits a particular method. An exception breakpoint set on a particular Java exception An expression breakpoint stops when a condition either becomes true or it changes
Eclipse Debugger Overview 39 Step Controls Step through the execution of the program line-by-line. Shortcuts F5 Step Into F6 Step Over F7 Step Return F8 Resume Ctrl+Shift+B Toggle Breakpoint Ctrl+Shift+I Inspect
Keep in Mind 40 A reference is a variable that stores the memory address where an object is temporarily stored in the stack or the special reference null. An object can be referenced by multiple references == operator is used to compare two references It returns true if the two references refer to the same object = operator makes a reference variable refer to another object. operator allows the selection of object s method or access to its fields There are only eight primitive types in Java (byte, short, int, long, float, double, char, and boolean). Any other type including String is a reference type All variables of a reference type are objects and are accessed via a reference
Keep in Mind 41 Reference types 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) For reference types and Strings, equals should be used instead of == to test if two objects have identical states In order to enforce encapsulation, use accessors and mutators to access to an object s private fields Garbage collection Automatic reclaiming of unreferenced memory