Class design. int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Chapter 4: Writing Classes
Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
Arrays Clark Savage Turner, J.D., Ph.D. Copyright © 2000 by C Scheftic. All rights reserved. These notes do rely heavily.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 One-Dimensional (1-D) Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration.
Java Unit 9: Arrays Declaring and Processing Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections.
Text Book: M. T. Goodrich and R. Tamassia, "Data Structures and Algorithms in Java," 4th edition, 2006, Wiley & Sons, Inc., ISBN Text Book:
Writing Classes (Chapter 4)
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
Chapter 8 Arrays and Strings
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
COS 312 DAY 12 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress report due Assignment corrected 1 MIA – 2 A’s, 2 B’s, 1 D, 1 F and 1 MIA – Code\pig.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
 2005 Pearson Education, Inc. All rights reserved Arrays.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
COMP 14 Introduction to Programming Mr. Joshua Stough March 23, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Lecture 5 array declaration and instantiation array reference
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Chapter 4: Writing Classes
More Object Oriented Programming
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Anatomy of a Method.
Object Oriented Programming Review
Visual Programming COMP-315
Arrays.
Presentation transcript:

Class design

int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations Method declarations

Method Types There can be various types of methods (behavior declarations) –access methods : read or display states (or those that can be derived) –predicate methods : test the truth of some conditions –action methods, e.g., print –constructors: a special type of methods they have the same name as the class –there may be more than one constructor per class (overloaded constructors) they do not return any value –it has no return type, not even void they initialize objects of the class, using the new construct: –e.g. m1 = new Month() ; you do not have to define a constructor –the value of the state variables have default value

Example: The Account Class We define an Account class to model a bank account In our Account class we could define the following data: –rate, a double –acctNumber, an integer –acctName, a string –balance, an integer We might also define the following methods: –Account constructor, to set up the object –withdraw method, to withdraw from the account –addInterest method, to add interest –toString method, returns a string describing the current state

Example: The Coin Class We define a Coin class to model a coin in a game In our Coin class we could define the following data: –face, an integer that represents the current face –HEADS and TAILS, integer constants that represent the two possible states We might also define the following methods: –Coin constructor, to set up the object (assume initially the coin’s face is “TAIL”, represented by integer 0) –flip method, to flip the coin –getFace method, to return the current face –toString method, returns a string describing the current state

int face = 0; class Coin coin1: Coin face = 0 coin2: Coin face = 0 public static void main (String[] args) { Coin coin1 = new Coin(); Coin coin2 = new Coin(); coin2.flip(); } Example of Instances of a Class: The Two Coin Objects

int face = 0; class Coin coin1: Coin face = 0 coin2: Coin face = 1 public static void main (String[] args) { Coin coin1 = new Coin(); Coin coin2 = new Coin(); coin2.flip(); }

Example: Account and Transactions public class Account { public final double RATE = 0.035; public long acctNumber; public String acctName; public double balance; public Account (String owner, long account, double initial) { acctName = owner; acctNumber = account; balance = initial; } public double deposit (double amount) { balance = balance + amount; return balance; } … } public static void main (String[] args) { Account aliceAcct = new Account (“Alice", 11111, ); Account bobAcct = new Account (“Bob", 22222, ); Account charlesAcct = new Account (“Charles", 33333, ); bobAcct.deposit (30.00); … }

Example: The Three Account Objects in Transactions aliceAcct: Account rate = acctNumber = acctName = “Alice” balance = bobAcct: Account rate = acctNumber = acctName = “Bob” balance = charlesAcct: Account rate = acctNumber = acctName = “Charles” balance = public static void main (String[] args) { Account aliceAcct = new Account (“Alice", 11111, ); Account bobAcct = new Account (“Bob", 22222, ); Account charlesAcct = new Account (“Charles", 33333, ); bobAcct.deposit (30.00); … }

Example: The Three Account Objects in Transactions public static void main (String[] args) { Account aliceAcct = new Account (“Alice", 11111, ); Account bobAcct = new Account (“Bob", 22222, ); Account charlesAcct = new Account (“Charles", 33333, ); bobAcct.deposit (30.00); … } aliceAcct: Account rate = acctNumber = acctName = “Alice” balance = bobAcct: Account rate = acctNumber = acctName = “Bob” balance = charlesAcct: Account rate = acctNumber = acctName = “Charles” balance =

Data Declarations: Class/Static Variables Sometimes it is useful if all instances of objects of a class share the same copy of a variable, e.g., –common constant variables –global statistics –the number of instances of objects created from a class Declare variables using keyword static to create only one copy of the variable Such variables are called static or class variables Class/static variables are accessible to all methods in the class

Keeping Track of Account Objects We want to keep track of the number of Account objects we ever created In our Account class, we could add the following data: –static int counter, an integer that represents the number of accounts we ever created –since counter is static, it is shared by all account objects –in constructor, we increase counter by 1 public class Account { public final double RATE = 0.035;public long acctNumber; public String acctName;public double balance; public static int counter = 0; // NEW public Account (String owner, long account, double initial) { acctName = owner; acctNumber = account; balance = initial; counter ++; // NEW }

Example: The Account Objects Acount.counter 0

Example: The Account Objects Acount.counter 1 aliceAcct: Account acctNumber = acctName = “Alice” balance = After Account aliceAcct = new Account (“Alice", 11111, );

Example: The Account Objects Acount.counter 2 aliceAcct: Account acctNumber = acctName = “Alice” balance = bobAcct: Account acctNumber = acctName = “Bob” balance = After Account bobAcct = new Account (“Bob", 2222, );

Example: The Account Objects Acount.counter 3 aliceAcct: Account acctNumber = acctName = “Alice” balance = bobAcct: Account acctNumber = acctName = “Bob” balance = charlesAcct: Account acctNumber = acctName = “Charles” balance = After Account charlesAcct = new Account (“Charles", 33333, );

Method Declarations: Instance and Static Instance methods: reflect the behaviors of objects created from the class –invocation: inside class definition: just call the method name outside class definition: objVar.methodName(…) –can access both instance and class/static variables Static/class methods –invocation: inside class definition: just call the method name outside class definition: ClassName.methodName(…) –declare methods using keyword static for such methods –can access only class/static variables (why?)

Keeping Track of Account Objects After adding: –static int counter = 0; We might want to add a static method: –public static int getNumberOfAccounts() { return counter; }

Class-Scope Variables (class and instance) and Methods in a Class can access cannot accesscan access static/class method static/class variable instance variable instance method Accessibility of variables in methods defined in the same class

Calling a Method Each time a method is called, each actual argument in the invocation is copied into the corresponding formal argument –if a value type, then it is the value that is copied –if a reference type, then it is the reference that is copied The formal argument and the actual argument are different variables, with different memory locations, even if they have the same name

Calling a Method: Value public int SquareSum (int num1, int num2) { num1 = num1 + num2; return num1 * num1; } int num = SquareSum (num1, num2); int num2 = 3; int num1 = 2; 2 3 num1 num2 2 3 num1 num2 5 0 num 25

Calling a Method: Reference static void doubleBalance(Account act) { double balance = act.getBalance(); act.setBalance( balance * 2 ); } doubleBalance (bobAcct); Account bobAcct = new Account(“Bob”, 22222, 200.0); acctNumber = acctName = “Bob” balance = bobAcct act balance double balance = 0;

Example: Parameter Passing public class Num { private int value; public Num(int update) { value = update; } public void setValue(int update) { value = update; } public String toString() { return value + “”; } }

Tracing the Parameters: Before changeValues() public static void main(String[] args) { int a1 = 111; Num a2 = new Num(222); Num a3 = new Num(333); tester.changeValues(a1, a2, a3); a1 f1f2f3 a2a public void changeValue(int f1, Num f2, Num f3) { f1 = 999; f2.setValue(888); f3 = new Num(777); }

Tracing the Parameters: In tester.changeValues(a1, a2, a3) a1 f1f2f3 a2a public static void main(String[] args) { int a1 = 111; Num a2 = new Num(222); Num a3 = new Num(333); tester.changeValues(a1, a2, a3); public void changeValue(int f1, Num f2, Num f3) { f1 = 999; f2.setValue(888); f3 = new Num(777); }

Tracing the Parameters: f1=999 a1 f1f2f3 a2a public static void main(String[] args) { int a1 = 111; Num a2 = new Num(222); Num a3 = new Num(333); tester.changeValues(a1, a2, a3); public void changeValue(int f1, Num f2, Num f3) { f1 = 999; f2.setValue(888); f3 = new Num(777); }

Tracing the Parameters: f2.setValue(888) a1 f1f2f3 a2a public static void main(String[] args) { int a1 = 111; Num a2 = new Num(222); Num a3 = new Num(333); tester.changeValues(a1, a2, a3); public void changeValue(int f1, Num f2, Num f3) { f1 = 999; f2.setValue(888); f3 = new Num(777); }

Tracing the Parameters: f3 = new Num(777) a1 f1f2f3 a2a public static void main(String[] args) { int a1 = 111; Num a2 = new Num(222); Num a3 = new Num(333); tester.changeValues(a1, a2, a3); public void changeValue(int f1, Num f2, Num f3) { f1 = 999; f2.setValue(888); f3 = new Num(777); }

Tracing the Parameters: Return a1 f1f2f3 a2a public static void main(String[] args) { int a1 = 111; Num a2 = new Num(222); Num a3 = new Num(333); tester.changeValues(a1, a2, a3); public void changeValue(int f1, Num f2, Num f3) { f1 = 999; f2.setValue(888); f3 = new Num(777); }

Arrays

Arrays: Declaration An array stores multiple values of the same type If the type is a primitive type, each element contains one value of the declared type boolean[] flags; // declare flags flags = new boolean[20]; // now flags is reference to another array flags = new boolean[10]; // declare variable grades; create an array; make grades a reference of the array int[] grades = new int[12]; // a less readable format int grades2[];

Arrays: Elements Refer to particular element in the array by position number (called index) int[] grades = new int[12]; grades[2] = 10; The index starts from 0; thus the index value must be between 0 to N-1, where N is the length of the array –for example, for the preceding array grades, it can be indexed only using the numbers 0 to 11

Array: An Array of Values A 12-element array of values grades[ 11 ] grades[ 10 ] grades[ 9 ] grades[ 8] grades[ 7 ] grades[ 4 ] grades[ 3 ] grades[ 2 ] grades[ 1 ] grades[ 0 ] grades[ 6 ] grades[ 5 ] position number (index or subscript) of the element within array grades grades int[] grades = new int[12]; grades[0] = -45; … grades[11] = -78;

Arrays: Declaration An array can also store multiple objects: each element of the array is a reference to an object of the declared type Month[] months; months = new Month[12]; String[] codes = new String[26];

Array: An Array of Objects A 12-element array of Month objects ref to obj 0 ref to obj 1 ref to obj 2 ref to obj 3 ref to obj 4 ref to obj 5 ref to obj 6 ref to obj 7 ref to obj 8 ref to obj 9months[ 9 ] months[ 8] months[ 7 ] months[ 4 ] months[ 3 ] months[ 2 ] months[ 1 ] months[ 0 ] months[ 6 ] months[ 5 ] position number (index or subscript) of the element within array months months ref to obj 10months[ 10 ] ref to obj 11months[ 11 ] Month[] months; months = new Month[12]; for (int i = 0; i < 12; i++) months[i] = new Month(i+1, 2005);

Shortcut: Array Initializer List An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas –allocate space for the array – number of elements in initializer list determines the size of array –elements in array are initialized with the values in the initializer list The new operator is not used Examples: int[] units = {147, 323, 89, 933, 540}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'}; String[] wordList = {“cs112“, “computer", “television"}; Month[] longMonths = {new Month(1, 2005), new Month(3, 2005), new Month(5, 2005), new Month(7, 2005), new Month(8, 2005), new Month(10, 2005), new Month(12, 2005) };

Shortcut: Enumerate Array Elements There is a special for statement to enumerate array elements: Example: int[] primes = {2, 3, 5, 7, 11}; for (int i : primes) System.out.println ( i + “ “);

Arrays as Objects In Java, an array is considered as an object Implication: –has attributes: e.g., the length attribute –parameter passing will be the same as object

39 Array: length Each array has a public constant called length that stores the size of the array –once an array is created, it has a fixed size –we will see ArrayList, a dynamic array next class It is referenced using the array name (just like any other object): grades.length Note that length holds the number of elements, not the largest index, e.g., for (int index=0; index < grades.length; index++) grades[index] = scan.nextInt();

Arrays as Parameters An entire array can be passed to a method as a parameter –like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other –changing an array element in the method changes the original An array element can be passed to a method as well, and follow the parameter passing rules of that element's type

Calling a Method: Array Reference static void doubleArray (int[] array) doubleArray( array ); int[] array = {1, 2, 3}; array { for (int i = 0; i < array.length; i++) array[i] *= 2; } i Each time a method is called, the actual arguments in the invocation are copied into the formal arguments –if a value type, then it is the value that is copied –if a reference type, then it is the reference that is copied The formal argument and the actual argument are different variables, with different memory locations array = new int[] {2, 4, 6, 8};

Example: Command-Line Arguments The signature of the main method indicates that it takes an array of String objects as a parameter These values come from command-line arguments that are provided when the interpreter is invoked For example, the following invocation of the interpreter passes an array of two String objects into main method: > java NameTag Howdy John The strings “ Howdy ” and “ John ” are stored at indexes 0- 1 of the String array args

Example: Using the Elements of an Array as Counters Use array elements to keep track of number of occurrences of different values –create an array with size of the number of possible values –each element of the array keeps track of the number of occurrences of one value –when a possibility occurs, increase the array element by one may need to map from value to index

Example: Using the Elements of an Array as Counters Read a sequence of integers between 1 to 10 until user inputs 0; keep track of number of occurrences of 1 to 10: int[] counters = new int[10]; int num; while ( (num=scan.nextInt()) != 0) counters[num-1]++; Count the number of lower-case characters in a line: int[] counters = new int[26]; String line = scan.nextLine(); for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (‘a’ <= ch && ch <= ‘z’) counters[ch-’a’]++;

45 Two-Dimensional Arrays A one-dimensional array stores a simple list of values A two-dimensional array can be thought of as a table of values, with rows and columns A two-dimensional array element is referenced using two index values To be precise, a two-dimensional array in Java is an array of arrays

Two-Dimensional Arrays A rectangle two-dimensional array with three rows and four columns. Row 0 Row 1 Row 2 Column 1Column 0Column 2Column 3 a[0][0]a[0][3]a[0][1]a[0][2] a[1][0]a[1][3]a[1][1]a[1][2] a[2][0]a[2][3] a[2][2] Column index (or subscript) Row index (or subscript) Array name a[2][1]

47 Two-dimensional Arrays: Initializer An initializer list can be used to create and set up a two-dimensional array Each element in the list is itself an initializer list Each array dimension has its own length constant

Initializer: Example public class Test2DArray { public static void main(String[] args) { int[][] days = { {1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {0} }; for (int i = 0; i < days.length; i++) { for (int j = 0; j < days[i].length; j++) System.out.print( days[i][j] ); System.out.println (); } } }

49 Multidimensional Arrays An array can have as many dimensions as needed, creating a multidimensional array Each dimension subdivides the previous one into the specified number of elements Each array dimension has its own length constant Because each dimension is an array of array references, the arrays within one dimension could be of different lengths