Date post: | 21-Dec-2015 |
Category: |
Documents |
View: | 225 times |
Download: | 0 times |
int month;int year
class Month
Defining Classes
• A class contains data declarations (state) and method declarations (behaviors)
Data declarationsData declarations
Method declarationsMethod 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 = 0public 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
Example of Instances of a Class: The Two Coin Objects
int face = 0;
class Coin
coin1: Coin
face = 0
coin2: Coin
face = 1public 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, 100.00);
Account bobAcct = new Account (“Bob", 22222, 200.00);
Account charlesAcct = new Account (“Charles", 33333, 300.00);
bobAcct.deposit (30.00); …}
Example: The Three Account Objects in Transactions
aliceAcct: Account
rate = 0.035acctNumber = 11111acctName = “Alice”balance = 100.00
bobAcct: Account
rate = 0.035acctNumber = 22222acctName = “Bob”balance = 200.00
charlesAcct: Account
rate = 0.035acctNumber = 33333acctName = “Charles”balance = 300.00
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: 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); …}
aliceAcct: Account
rate = 0.035acctNumber = 11111acctName = “Alice”balance = 100.00
bobAcct: Account
rate = 0.035acctNumber = 22222acctName = “Bob”balance = 230.00
charlesAcct: Account
rate = 0.035acctNumber = 33333acctName = “Charles”balance = 300.00
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
1aliceAcct: Account
acctNumber = 11111acctName = “Alice”balance = 100.00
After Account aliceAcct = new Account (“Alice", 11111, 100.00);
Example: The Account Objects
Acount.counter
2aliceAcct: Account
acctNumber = 11111acctName = “Alice”balance = 100.00
bobAcct: Account
acctNumber = 22222acctName = “Bob”balance = 200.00
After Account bobAcct = new Account (“Bob", 2222, 200.00);
Example: The Account Objects
Acount.counter
3aliceAcct: Account
acctNumber = 11111acctName = “Alice”balance = 100.00
bobAcct: Account
acctNumber = 22222acctName = “Bob”balance = 200.00
charlesAcct: Account
acctNumber = 33333acctName = “Charles”balance = 300.00
After Account charlesAcct = new Account (“Charles", 33333, 300.00);
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 can access
cannot access can access
static/classmethod
static/classvariable
instancevariable
instancemethod
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
0num 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 = 22222acctName = “Bob”balance = 200.00
bobAcct
act
balance
balance
double balance = 0;
0
200
400.00
Example: Parameter Passingpublic 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
f1 f2 f3
a2 a3
111 222 333
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
f1 f2 f3
a2 a3
111 222 333
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);}
Tracing the Parameters: f1=999
a1
f1 f2 f3
a2 a3
111 222 333
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);}
Tracing the Parameters: f2.setValue(888)
a1
f1 f2 f3
a2 a3
111 888 333
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);}
Tracing the Parameters: f3 = new Num(777)
a1
f1 f2 f3
a2 a3
111 888 333
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);}
Tracing the Parameters:Return
a1
f1 f2 f3
a2 a3
111 888 333
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);}
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.
-45
6
0
72
1543
-89
0
62
-3
1
6453
-78grades[ 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 usedExamples: 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
array
123
246
{ 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.
2468
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 0 Column 2 Column 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