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

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

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

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

Objects and Classes -- Introduction

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

Chapter 4: Writing Classes

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

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

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

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

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) Instance Data. COMP Objects 2 1

Lecture 5: Methods CS2301

Chapter 4 Defining Classes I

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) COMP 202 Objects 2 1

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

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

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

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

ECE 122. Engineering Problem Solving with Java

AP CS Unit 3: Control Structures Notes

Chapter 5: Writing Classes and Enums

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

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods

Container Vs. Definition Classes. Container Class

CS111: PROGRAMMING LANGUAGE II

CS1004: Intro to CS in Java, Spring 2005

Lecture #6-7 Methods

Introduction to Programming Using Java (98-388)

ECE 122. Engineering Problem Solving with Java

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

CHAPTER 7 OBJECTS AND CLASSES

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Chapter 6 Introduction to Defining Classes

CHAPTER 7 OBJECTS AND CLASSES

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

ECE 122. Engineering Problem Solving with Java

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Computer Science II (20082) Week 1: Review and Inheritance

Assignment 1 due Monday at 11:59pm

Defining Classes and Methods

CS112 Lecture: Defining Instantiable Classes

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

Chapter 3 Function Overloading

Java: introduction to object-oriented features

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)

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

&KDSWHU(QKDQFLQJ&ODVVHV

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

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

Introduction to Programming (Java) 4/12

Computer Science II (20073) Week 1: Review and Inheritance

CSC Java Programming, Fall Java Data Types and Control Constructs

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

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Chapter 5: Enhancing Classes

Introduction to Computer Science Unit 2. Notes

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

CS1004: Intro to CS in Java, Spring 2005

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

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

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

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

Where do objects come from? Good question!

Array. Prepared By - Rifat Shahriyar

Programming Language Concepts: Lecture 2

M e t h o d s a n d P a r a m e t e r s

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

COP 3330 Final Exam Review

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CS110D: PROGRAMMING LANGUAGE I

Methods and Functions

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Packages & Random and Math Classes

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Object Oriented Programming

CMSC 132: Object-Oriented Programming II

Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes

Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

( &% class MyClass { }

An introduction to Java II

Methods. CSE 114, Computer Science 1 Stony Brook University

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 3 Classes. Activity The class as a file drawer of methods. Activity Referencing static methods

Transcription:

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

Static member variables So far: Member variables were instance variables Every object instance has its own set of these variables Member variables can also be static static variables are also called class variables Shared by all objects/instances of a class I.e., there is only one copy of this variable If one object changes the value of a static variable, all other objects see and access the new value private static int count = 0; Example use: Increase count whenever the Constructor is called Keeps track of the number of objects created; COMP 202 Objects 3 2

Static methods Static methods can be executed without an object of the class instantiated Static methods can not access member variables because they 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 COMP 202 Objects 3 3

Class dependencies Stand alone Classes that do not depend or need other classes to run Dependencies When a program calls methods of other classes and/or instantiates objects of other classes. eg. Bank uses Client class eg. use of String and Scanner classes Aggregate Classes A class that is composed from multiple other classes COMP 202 Objects 3 4

Aggregate Classes A class that defines an object as one of its class variables has created a dependency between the class they are building and the object 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 COMP 202 Objects 3 5

public class Account { private double balance; //member variables public Account (double startbalance) { balance = startbalance; public boolean withdrawal (double amount) { if (amount < 0 balance < amount) return false; else { balance = amount; return true; public double deposit (double amount) { balance += amount; return balance; COMP 202 Objects 3 6

public class Client { private Account checking; //member variables private Account savings; public Client (double checkingbalance, double savingsbalance) { checking = new Account(checkingBalance); savings = new Account(savingsBalance); public boolean withdrawalchecking (double amount) { return (checking.withdrawal(amount)); public boolean withdrawalsavings (double amount){ return (savings.withdrawal(amount)); COMP 202 Objects 3 7

public boolean transfer (char fromaccount, double amount) { boolean returnvalue=false; switch(fromaccount) { case 'c': if (checking.withdrawal(amount)){ savings.deposit(amount); returnvalue = true; else returnvalue = false; break; case 's': if (savings.withdrawal(amount)){ checking.deposit(amount); returnvalue = true; else returnvalue = false; return returnvalue; COMP 202 Objects 3 8

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 COMP 202 Objects 3 9

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 COMP 202 Objects 3 10

Passing Objects to Methods Parameters in a Java method are passed by value This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) i.e. not the real/original value Passing parameters is essentially an assignment When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other COMP 202 Objects 3 11

ParamPassTest.java public class ParamPassTest { public static void main (String args[]) { int param = 3; ParamPassTest obj = new ParamPassTest(); obj.addone(param); System.out.println("main param is " + param); public void addone(int p) { p = p + 1; System.out.println("addOne param is " + p); Example of a standard copy pass of an integer parameter: How does it look in memory while executing? COMP 202 Objects 3 12

Parameter Passing with Objects In a Java statement such as Cat curly = new Cat(); the variable curly is not an object, it is simply a reference to an object (hence the term reference variable). Reference variable curly 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); Object Cat object COMP 202 Objects 3 13

Parameter Passing with Objects 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. However, what does it mean to say that two reference variables have the same value? It means that both variables refer to the same object: Reference variable curly thecat Object Cat object Within veterinarian() you can now update the Cat object via variable thecat. COMP 202 Objects 3 14

Parameter Passing with Objects curly An object can have multiple references to it. In this example, we still have just the one object, but it is being referenced by two different variables. But if you change the value of the variable thecat within veterinarian() so that it refers to a different object: thecat = new Cat(); Then the value of variable curly within the calling method remains unchanged, and variable curly will still refer to the same Cat object that it always did: Cat object thecat another Cat object COMP 202 Objects 3 15

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 COMP 202 Objects 3 16

ParameterPassing.java 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"); COMP 202 Objects 3 17

ParameterTester.java class ParameterTester { public void changevalues (int f1, Num f2, Num f3) { System.out.println ("Before changing the 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"); COMP 202 Objects 3 18

Num.java class Num { private int value; public Num (int update) { value = update; public void setvalue (int update) { value = update; public String tostring () { return value + ""; COMP 202 Objects 3 19

Data Scope The scope of data is the area in a program in which that data can be used (referenced) 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 COMP 202 Objects 3 20

Scope A variable's scope is the region of a program within which the variable can be referred to by its simple name. Secondarily, scope also determines when the system creates and destroys memory for the variable. COMP 202 Objects 3 21

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 class MyClass {... member variable declarations... Scope public void amethod(method parameters) {... local variable declarations... COMP 202 Objects 3 22

Scope 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) You declare local variables within a block of code. In general, the scope of a local variable extends from its declaration to the end of the code block in which it was declared. Normally defined by the close 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. COMP 202 Objects 3 23

Scope Example 1 Consider the following example: 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 header, or the println method call needs to be moved into the for loop. COMP 202 Objects 3 24

Scope Example 2 public class Ex2 { int x; String y; public int sum(int x, int y) { int z = x + y; return z; public String tostring() { return y + x; public String message(int y){ int z = x + y; return "Value = " + z; Who is referencing what? COMP 202 Objects 3 25

this reference Allows an object to refer to itself Most common use in Constructor method public Client (double checkingbalance, double savingsbalance){ balchecking = checkingbalance; balsaving = savingsbalance; vs. public Client (double balchecking, double balsavings){ this.balchecking = balchecking; this.balsaving = balsavings; Allows parameters and/or local variables to have same name as member variables. Member variables can always be referred to through this reference. COMP 202 Objects 3 26

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 (how to call it) From the external view: an object is an encapsulated entity, providing a set of specific services These services define the interface to the object An object is an abstraction, hiding details from the rest of the system COMP 202 Objects 3 27

Encapsulation An object should be self governing Any changes to the object's state (its variables) should be accomplished ONLY by that object's methods We should make it 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 it should not have to be aware of how those services are accomplished COMP 202 Objects 3 28

Encapsulation An encapsulated object can be thought of as a black box Its inner workings are hidden to the client, which only invokes the interface methods Client Methods Data COMP 202 Objects 3 29

Visibility Modifiers In Java, we accomplish encapsulation through the appropriate use of visibility modifiers public and private COMP 202 Objects 3 30

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 compiler must be able to determine which version of the method is being invoked by analyzing the parameters The return type of the method is not part of the signature COMP 202 Objects 3 31

Overloading Methods Version 1 Version 2 float tryme (int x) { return x +.375; Invocation float tryme (int x, float y) { return x*y; result = tryme (25, 4.32) COMP 202 Objects 3 32

Overloaded Methods 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); COMP 202 Objects 3 33

Part 5 Thinking Like A Programmer (Stepwise refinement & Method decomposition) COMP 202 Objects 3 34

Stepwise Refinement The user wants to be able to input a fixed number of integers into a program and then have it display a menu where the user can select between summing or averaging the values. When the program ends it will write the numbers to the screen together with the sum and average. The numbers are listed vertically down with proper titles for the numbers, sum and average. How to solve this problem? COMP 202 Objects 3 35

Step 1: Identify the Parts The user wants to be able to input a fixed number of integers into a program and then have it display a menu where the user can select between summing or averaging the values. When the program ends it will write the numbers to the screen together with the sum and average. The numbers are listed vertically down with proper titles for the numbers, sum and average. The user wants to be able to input a fixed number of integers into a program and then have it display a menu where the user can select between summing or averaging the values. When the program ends it will write the numbers to the screen together with the sum and average. The numbers are listed vertically down with proper titles for the numbers, sum and average. COMP 202 Objects 3 36

Step 2: Order the Parts The user wants to be able to input a fixed number of integers into a program and then have it display a menu where the user can select between summing or averaging the values. When the program ends it will write the numbers to the screen together with the sum and average. The numbers are listed vertically down with proper titles for the numbers, sum and average. First Second Third (choice) Fourth Fifth Sixth COMP 202 Objects 3 37

Step 3: Write Code for A Part From easy to harder Draw flowchart if needed Write sub steps in English if needed Use: Encapsulation, and Method decomposition COMP 202 Objects 3 38

Notes Encapsulation We have already covered this Objectify things by creating a class that encompasses the desired characteristics Identify state (variables) and activities (methods) Method decomposition and parameters As you encapsulate, decisions need to be made concerning the format of your methods and their parameters Which methods are service methods Which methods are interface methods to clients Which should be private and which public COMP 202 Objects 3 39

Step 4: Now Assemble into a Program COMP 202 Objects 3 40