1 / 49

Class design

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)

jonah
Download Presentation

Class design

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Class design

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

  3. 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

  4. 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

  5. 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

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

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

  8. 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, 100.00); Account bobAcct = new Account (“Bob", 22222, 200.00); Account charlesAcct = new Account (“Charles", 33333, 300.00); bobAcct.deposit (30.00); … } Example: Account and Transactions

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

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

  11. 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

  12. 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 }

  13. Example: The Account Objects 0 Acount.counter

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

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

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

  17. 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?)

  18. 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; }

  19. Class-Scope Variables (class and instance)and Methods in a Class static/classmethod instancemethod can access can access static/classvariable cannot access can access instancevariable Accessibility of variables in methods defined in the same class

  20. 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

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

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

  23. 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 + “”; } }

  24. a1 a2 a3 222 333 111 f1 f2 f3 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); public void changeValue(int f1, Num f2, Num f3){ f1 = 999; f2.setValue(888); f3 = new Num(777); }

  25. Tracing the Parameters: In tester.changeValues(a1, a2, a3) a1 a2 a3 222 333 111 f1 f2 f3 111 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); }

  26. Tracing the Parameters: f1=999 a1 a2 a3 222 333 111 f1 f2 f3 999 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); }

  27. Tracing the Parameters: f2.setValue(888) a1 a2 a3 888 333 111 f1 f2 f3 999 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); }

  28. Tracing the Parameters: f3 = new Num(777) a1 a2 a3 888 333 111 f1 f2 f3 999 777 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); }

  29. Tracing the Parameters:Return a1 a2 a3 888 333 111 f1 f2 f3 777 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); }

  30. Arrays

  31. 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[];

  32. Arrays: Elements • Refer to particular element in the array by positionnumber (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

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

  34. 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];

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

  36. 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) };

  37. 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 + “ “);

  38. 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();

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

  41. 2 1 { for (int i = 0; i < array.length; i++) array[i] *= 2;} 2 4 i 3 6 2 4 6 Calling a Method: Array Reference • 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. int[] array = {1, 2, 3}; array doubleArray( array ); static void doubleArray (int[] array) array array = new int[] {2, 4, 6, 8}; 8

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

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

  44. 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

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

  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

  48. 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

More Related