COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

Similar documents
COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference

Objects and Classes -- Introduction

CSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277

Anatomy of a Class Encapsulation Anatomy of a Method

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Chapter 4: Writing Classes

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Inheritance. Quick Review of Last Lecture. November 12, Passing Arguments. Passing Arguments. Variable Assignment Revisited

Chapter 4 Defining Classes I

What will this print?

Software Development Activities. Establishing the requirements. Software Design. CMPT 126: Lecture 8 Object-Oriented Design

CMPT 126: Lecture 8 Object-Oriented Design

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Lecture 5: Methods CS2301

Container Vs. Definition Classes. Container Class

ECE 122. Engineering Problem Solving with Java

Packages & Random and Math Classes

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

OBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com

( &% class MyClass { }

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Chapter 6 Introduction to Defining Classes

Defining Classes and Methods

ECE 122. Engineering Problem Solving with Java

Objects and Classes: Working with the State and Behavior of Objects

Writing Classes Chapter 5. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Assignment 1 due Monday at 11:59pm

CS110D: PROGRAMMING LANGUAGE I

CHAPTER 7 OBJECTS AND CLASSES

JAVA GUI PROGRAMMING REVISION TOUR III

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Review. these are the instance variables. these are parameters to the methods

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Introduction to Programming Using Java (98-388)

LECTURE 2 (Gaya College of Engineering)

CHAPTER 7 OBJECTS AND CLASSES

CS1004: Intro to CS in Java, Spring 2005

&KDSWHU(QKDQFLQJ&ODVVHV

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

AP CS Unit 3: Control Structures Notes

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

ECE 122. Engineering Problem Solving with Java

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Lecture #6-7 Methods

Cmpt 135 Assignment 2: Solutions and Marking Rubric Feb 22 nd 2016 Due: Mar 4th 11:59pm

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

CS 231 Data Structures and Algorithms, Fall 2016

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Conversions and Overloading : Overloading

Lecture 06: Classes and Objects

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Object Oriented Programming

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

STUDENT LESSON A5 Designing and Using Classes

COP 3330 Final Exam Review

Java: introduction to object-oriented features

Introduction to Programming Written Examination

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Chapter 5: Enhancing Classes

3.1 Class Declaration

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Methods and Data (Savitch, Chapter 5)

Day 2. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Creating Classes and Objects

Zheng-Liang Lu Java Programming 45 / 79

CMSC 331 Second Midterm Exam

Object Oriented Programming

Chapter 6 Methods. Dr. Hikmat Jaber

Questions Answer Key Questions Answer Key Questions Answer Key

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Java Magistère BFA

Agenda: Notes on Chapter 3. Create a class with constructors and methods.

this keyword (1). this with constructor (2). cisc3120 design and implementation of software applications I spring 2015 lecture # I.

Defining Classes and Methods

CS 251 Intermediate Programming Methods and Classes

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

CS 251 Intermediate Programming Methods and More

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Tutorial 4. Values and References. Add One A. Add One B. Add One C

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Lecture 7: Classes and Objects CS2301

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

COMP-202: Foundations of Programming. Lecture 10: Method Overloading and Passing Objects to Methods. Sandeep Manjanna, Summer 2015

Programming Language Concepts: Lecture 2

C10: Garbage Collection and Constructors

Object Oriented Modeling

Transcription:

COMP-202 Objects, Part III

Lecture Outline Static Member Variables Parameter Passing Scopes Encapsulation Overloaded Methods Foundations of Object-Orientation 2

Static Member Variables So far, member variables were instance variables Every object instance has its own copy of each declared instance variable Member variables can also be static static variables are also called class variables There is always only one instance of a static variable, shared by all objects / instances of a class If one object changes the value of a static variable, all other objects see and access the new value 3

Static Member Variable Example Provide unique sequential account numbers to each account Store the number in a static member variable of the class Account Increase the number in the constructor public class Account { static private int nextaccountnumber = 1; private double balance; private int accountnumber; public Account(double initialbalance) { balance = initialbalance; accountnumber = nextaccountnumber; nextaccountnumber++; 4

Static Methods Static methods can be executed without instantiating an object of the class Static methods Can not access member variables because member variables always belong to a specific object/instance Can access static variables and local variables All methods of Math class are static Math.abs(-5); main method is static 5

Calling Methods A method calls a method m1 of the same class: m1(...); Only the method name is needed A method calls a static method m1 of the class AnotherClass: AnotherClass.m1(); The class name appears as a prefix A method calls a non-static method m1 of another object which is referred to by the variable objvariable objvariable.m1(); 6

Class Dependencies Kinds of Dependencies between Classes When a program calls methods of other classes and/or instantiates objects of other classes e.g. Bank uses Client class e.g. Use of String and Scanner classes Aggregate Classes: a class that is composed from multiple other classes e.g. Client stores references to Account objects in its member variables 7

Aggregate Classes A class that defines an object variable as one of its class variables or instance variables has created a dependency between the class and the class of the variable Aggregate classes are classes that use other classes as variables, these can be: Built-in library classes (e.g. String) Your own classes Purchased / downloaded library classes 8

Student Example public class Student { private long id; private String name; private ArrayList courses; public Student(String name, long id) { this.name = name; this.id = id; courses = new ArrayList(); id : Student name courses : String : ArrayList 9

Parameter Passing Primitive parameters (byte, short, char, int, long, float, double) of a Java method are passed by value This means that a copy of the actual parameter (the value passed in) is stored in memory space allocated for the formal parameter Changing the local copy does not affect the value of the original Object parameters passed to a method are passed by reference: the actual parameter and the formal parameter become aliases of each other 10

ParamPassTest public class ParamPassTest {! public static void main (String args[]) {!! int param = 3;!! addone(param);!! System.out.println("main param is " + param);!! public static void addone(int p) {!! p = p + 1;!! System.out.println("addOne param is " + p);! What will be displayed? 11

Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable For primitive types: int num1 = 5; int num2 = 12; num2 = num1; Before After num1 5 num1 5 num2 12 num2 5 12

Object References Recall that an object reference holds the memory address of an object Rather than dealing with arbitrary addresses, we often depict a reference graphically as a pointer to an object ChessPiece bishop1 = new ChessPiece(); bishop1 13

Reference Assignment For object references, assignment copies the memory location: ChessPiece bishop1 = new ChessPiece(); ChessPiece bishop2 = new ChessPiece(); bishop2 = bishop1; Before bishop1 bishop1 After bishop2 bishop2 14

Parameter Passing With Objects (1) Consider a method declared as! public void veterinarian(cat thecat) {... If we call this method passing as a reference to a Cat object, what happens exactly?! Cat curly = new Cat(); veterinarian(curly); curly 15

Parameter Passing With Objects (2) public void main(..) { Cat curly = new Cat(); veterinarian(curly); curly public void veterinatian (Cat thecat) { thecat.moodswing(); thecat The value of the variable curly is passed by value, and the variable thecat within veterinarian() receives a copy of this value Variables curly and thecat now have the same value, i.e. they refer to the same object 16

Parameter Passing With Objects (3) public void main(..) { Cat curly = new Cat(); veterinarian(curly); curly public void veterinatian (Cat thecat) { thecat.moodswing(); thecat = new Cat(); thecat If one changes the value of the variable thecat within veterinarian(), the value of curly remains unchanged 17

Aliases Two or more references that refer to the same object are called aliases of each other One object (and its data) can be accessed using different variables Aliases can be useful, but should be managed carefully Changing the object s state (its variables) through one reference changes it for all of its aliases 18

Passing Objects to Methods Example In this example notice the following: What you do to a parameter inside a method may or may not have a permanent effect (outside the method) Note the difference between changing the reference and changing the object that the reference points to 19

Num public class Num { private int value; public Num(int initial) { value = initial; public void setvalue(int update) { value = update; public String tostring() { return value + ""; 20

ParameterTester public class ParameterTester { public void changevalues(int f1, Num f2, Num f3) { System.out.println("Before changing values:"); System.out.println("f1\tf2\tf3"); System.out.println(f1 + "\t" + f2 + "\t" + f3 + "\n"); f1 = 999; f2.setvalue(888); f3 = new Num (777); System.out.println ("After changing the values:"); System.out.println ("f1\tf2\tf3"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); 21

ParameterPassing public class ParameterPassing { public static void main(string[] args) { ParameterTester tester = new ParameterTester(); int a1 = 111; Num a2 = new Num(222); Num a3 = new Num(333); System.out.println("Before calling changevalues:"); System.out.println("a1\ta2\ta3"); System.out.println(a1 + "\t" + a2 + "\t" + a3 + "\n"); tester.changevalues(a1, a2, a3); System.out.println("After calling changevalues:"); System.out.println("a1\ta2\ta3"); System.out.println(a1 + "\t" + a2 + "\t" + a3 + "\n"); 22

Garbage Collection When an object no longer has any valid references to it, it can no longer be accessed by the program It is useless, and therefore called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use In some other languages, the programmer has the responsibility for performing garbage collection 23

Scope The scope of data is the area in a program in which that data can be used (referred to by it s name) The scope of data depends on where it is declared Member variables (instance variables and static variables) can be used by all methods of the class Restriction: static methods can only use static variables Data declared within a method can only be used in that method Data declared within a method is called local data The scope determines when memory is allocated to hold the data (and when it is released) 24

Different Scopes (1) class MyClass {... member_variable_declarations... public void amethod(formal_parameter_declarations) {... local_variable_declarations... The location of the variable declaration within your program establishes its scope and places it into one of these 3 categories: - member variables - method parameter - local variable 25

Different Scopes (3) Member Variables A member variable is a member of a class It is declared within a class but outside of any method A member variable's scope is the entire declaration of the class Local Variables (local data) Local variables are declared within a block of code The scope of a local variable extends from its declaration to the end of the code block in which it was declared (shown by the closing curly bracket) Parameter Variables (local data) Parameters are formal arguments to methods and are used to pass values into methods The scope of a parameter is the entire method for which it is a parameter. It is treated just like a local variable. 26

Scope Example class ScopeTest { int x; String y; int sum(int x, int y) { int z = x + y; return z; String tostring() { return y + x; String message(int y){ int z = x + y; return Value = + z; Which identifiers refer to what variable? 27

Scope in for Loops Variables declared in a for loop exist throughout the loop only for (int i = 0; i < 100; i++) {!... System.out.println("The value of i = " + i); The final line won't compile because the local variable i is out of scope. Either the variable declaration needs to be moved outside of the for statement block, or the println method call needs to be moved into the for loop. 28

this Reference Allows an object to refer to itself Most common use in constructor methods public Account(double balance) { this.balance = balance; Allows parameters and/or local variables to have the same name as member variables Member variables can always be referred to using the this reference 29

Encapsulation You can take one of two views of an object: Internal - the structure of its data, the algorithms used by its methods External - the interaction of the object with other objects in the program From the external view: An object is an encapsulated entity, providing a set of specific services, which define the interface of the object An object is an abstraction, hiding details from the rest of the system 30

Making Encapsulation Work An object should be self-governing Any changes to the object's state (its variables) should be accomplished only by that object's methods It should be difficult, if not impossible, for one object to "reach in" and alter another object's state The user of an object can request its services, but he / she should not have to be aware of how those services are accomplished 31

An Encapsulated Object An encapsulated object can be thought of as a black box Its inner workings are hidden to the client, which only invokes the interface (public) methods o : Object Client methods data 32

Overloading Methods Method overloading is the process of using the same method name for multiple methods The signature of each overloaded method must be unique The signature of a method is built from the method name, number, type, and order of the parameters The return type of the method is not part of this signature The compiler must be able to determine which version of the method is being invoked by analyzing the parameters 33

Overloaded Methods Example (1) Two methods with the same name but different signatures float tryme(int x) { return x + 0.375f; float tryme(int x, float y) { return x * y; result = tryme(25, 5.34f); Which one is invoked? 34

Overloaded Method Example (2) The println method is overloaded: println(string s) println(int i) println(double d) etc. The following lines invoke different versions of the println method: System.out.println("The total is:"); System.out.println(total); 35

Foundations of Object-Orientation Abstraction Extraction of essential properties while omitting inessential details. Information hiding (encapsulation) Separation of the external view from the internal details. Aspects that should not affect other parts of the system are made inaccessible. Modularity Decomposition into a set of cohesive and loosely coupled units; i.e. purposeful structuring. Classification (to be seen later in the course) 36