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

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

Anatomy of a Class Encapsulation Anatomy of a Method

Objects and Classes -- Introduction

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

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

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

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

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

Lecture 5: Methods CS2301

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

Chapter 4 Defining Classes I

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

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

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

AP CS Unit 3: Control Structures Notes

&KDSWHU(QKDQFLQJ&ODVVHV

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

CS1004: Intro to CS in Java, Spring 2005

CS1150 Principles of Computer Science Methods

Container Vs. Definition Classes. Container Class

Lecture #6-7 Methods

CS1150 Principles of Computer Science Methods

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

CS1083 Week 2: Arrays, ArrayList

Chapter 5: Enhancing Classes

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

Java Coding 3. Over & over again!

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

Introduction to Computer Science Unit 2. Notes

ECE 122. Engineering Problem Solving with Java

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

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

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

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

( &% class MyClass { }

CS111: PROGRAMMING LANGUAGE II

Chapter 5: Writing Classes and Enums

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

Chapter 5: Classes and Objects in Depth. Introduction to methods

CS110D: PROGRAMMING LANGUAGE I

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

CS1004: Intro to CS in Java, Spring 2005

Packages & Random and Math Classes

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

Chapter 6 Introduction to Defining Classes

ECE 122. Engineering Problem Solving with Java

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

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

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

CS111: PROGRAMMING LANGUAGE II

Introduction to Programming Using Java (98-388)

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

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

Programming with Java

CHAPTER 7 OBJECTS AND CLASSES

Methods. CSE 114, Computer Science 1 Stony Brook University

Assignment 1 due Monday at 11:59pm

Lecture Set 4: More About Methods and More About Operators

Introduction to Computer Science Unit 2. Notes

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

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

ECE 122. Engineering Problem Solving with Java

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

COP 3330 Final Exam Review

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

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

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

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

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

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

COMP 202 Java in one week

Methods and Functions

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

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

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

Objects and Classes Lecture 2

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

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

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

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

Introduction to Programming (Java) 4/12

CS 112 Introduction to Programming

LECTURE 2 (Gaya College of Engineering)

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 7 OBJECTS AND CLASSES

JAVA GUI PROGRAMMING REVISION TOUR III

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Lecture Set 4: More About Methods and More About Operators

Chapter 7 User-Defined Methods. Chapter Objectives

Introduction to Computer Science Unit 2. Exercises

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

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

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

COMP 202. Programming With Arrays

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Transcription:

COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 - Week 7 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 - Week 7 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 - Week 7 3

Calling Methods A method calls a method m1 of the same class: Only indicate method name: m1( ); A method calls a static method m1 of another class AnotherClass: AnotherClass.m1(); A method calls a non-static m1 of another object which is referred to by the variable objvariable objvariable.m1(); COMP 202 - Week 7 4

The calculator as a class with only static methods import java.util.scanner; public class CalcMain { public static void main(string[] args) { int op; double v1,v2,result; scan = new Scanner(System.in); System.out.println( Enter 0 to exit, 1 to add, 2 to subtract ); op=scan.nextint(); if (op==1 op==2) { System.out.print( Enter number: ); v1=scan.nextdouble(); System.out.print( Enter number: ); v2=scan.nextdouble(); if (op==1) result = CalcMain.add(v1,v2); else result = subtract(v1,v2); System.out.println( Result: +result); COMP 202 - Week 7 5

The calculator as a class with only static methods public static double add(double d1,double d2) { return d1+d2; public static double subtract(double d1,double d2) { return d1-d2; // etc COMP 202 - Week 7 6

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 - Week 7 7

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 - Week 7 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(); Student id name courses COMP 202 - Week 7 9

Parameter Passing 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 Changing the local copy does not affect the original Not true of objects: when an object is passed to a method, the actual parameter and the formal parameter become aliases of each other COMP 202 - Week 7 10

ParamPassTest.java 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); Example of a standard copy pass of an integer parameter: How does it look in memory while executing? COMP 202 - Week 7 11

Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable For primitive types: num1 5 Before num2 12 num2 = num1; num1 5 After num2 5 COMP 202 - Week 7 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 COMP 202 - Week 7 13

Reference Assignment For object references, assignment copies the memory location: bishop1 Before bishop2 = bishop1; bishop2 bishop1 After bishop2 COMP 202 - Week 7 14

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 Object Cat object 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); COMP 202 - Week 7 15

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 - Week 7 16

Parameter Passing with Objects 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: curly Cat object thecat another Cat object COMP 202 - Week 7 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 COMP 202 - Week 7 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 COMP 202 - Week 7 19

ParameterPassing.java 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"); COMP 202 - Week 7 20

ParameterTester.java public 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 - Week 7 21

Num.java public 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 - Week 7 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 COMP 202 - Week 7 23

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 - Week 7 24

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 - Week 7 25

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 - Week 7 26

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 - Week 7 27

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 if statement block, or the println method call needs to be moved into the for loop. COMP 202 - Week 7 28

Scope Example 2 class ex2 { 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; Who is referencing what? COMP 202 - Week 7 29

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; versus public Client (double balchecking, double balsavings){ this.balchecking = balchecking; this.balsavings = 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 - Week 7 30

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 - Week 7 31

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 - Week 7 32

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 - Week 7 33

Visibility Modifiers In Java, we accomplish encapsulation through the appropriate use of visibility modifiers public and private COMP 202 - Week 7 34

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 this signature COMP 202 - Week 7 35

Overloading Methods Version 1 Version 2 float tryme (int x) { return x+0.375f; Invocation float tryme (int x, float y) { return x*y; result = tryme (25, 4.32f) COMP 202 - Week 7 36

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 - Week 7 37

Part 5 Thinking Like A Programmer (Stepwise refinement & Method decomposition) COMP 202 - Week 7 38

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 - Week 7 39

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 - Week 7 40

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 - Week 7 41

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 - Week 7 42

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 - Week 7 43

Step 4: Now Assemble into a Program COMP 202 - Week 7 44