Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 6 Arrays and Interfaces.

Similar presentations


Presentation on theme: "Lecture 6 Arrays and Interfaces."— Presentation transcript:

1 Lecture 6 Arrays and Interfaces

2 Objectives Learn to use arrays. Learn to implement interfaces.
Default Arrays Array Initializers arraycopy Learn to implement interfaces. Discuss events. Introduce event listeners.

3 Arrays in Java In Java, arrays are objects.
In addition to the usual C operations they also have methods and attributes. The are declared differently than in C. There are two ways to declare an array. An array can be declared to contain a default value. An array can be declared using an array initializer to contain values we specify. Creating an array in Java is a two step process. First we create a reference (pointer) to an array object that can contain the correct variable type. Next, we reserve memory for the array an associate it with the reference.

4 Declaring Default Arrays
First we create the reference to the array. int[] x; Next we reserve the memory for the array and associate it with the reference. x = new int[12]; These can be combined into a single line. int[] x = new int[12]; The elements of the array will contain whatever is the default value of their type. for(int i = 0; i < 12; i++) System.out.printf("x[%d] = %d ", i, x[i]); This produces the following output x[0] = 0 x[1] = 0 x[2] = 0 x[3] = 0 ... The default value for an int is 0.

5 Array Initializer Declaring an array using an array initializer doesn’t require us to explicitly specify the number of items in the array. int[] y = {12, 8, 7, 3, 4, 0, -1, 5}; One of the attributes of an array is its size. System.out.printf(”y has length %d.", y.length); If you use an index that is out of bounds an exception will be thrown. If you do not catch it, your program will crash.

6 Passing Arrays to Functions
The following is a function that accepts an array as one of its parameters. static void arrayModifier(int[] p){ for (int i = 0; i < p.length; i++) p[i] = i; } The function is static so that we can call it without creating an object. Notice the parameter type is int[] (an array of ints). Recall that an array is an object, so modifying its elements will change the actual parameter. Notice the we can use the length attribute to avoid running off the end of the array.

7 Passing Arrays Functions
Here is an example of some code that uses our function. int[] x = new int[12]; System.out.println("Before function call."); for(int i = 0; i < 12; i++) System.out.printf("x[%d] = %d ", i, x[i]); System.out.printf("%n"); arrayModifier(x); System.out.println("After function call,");

8 Passing Arrays to Functions
Here is the output. Before function call. x[0] = 0 x[1] = 0 x[2] = 0 x[3] = 0 x[4] = 0 ... After function call, x[0] = 0 x[1] = 1 x[2] = 2 x[3] = 3 x[4] = 4 ... The function did modify the array entries. Notice this does not violate the call by value. The array that was passed as a parameter (the address in memory) did not change – the contents of the memory is what changed.

9 Array Operations Indexing arrays works just as it did in C.
There is a System method, arraycopy, that can be used to copy an array. arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src – the source array. srcPos – the position to begin copying from. dest – the destination array. destPos – the position to begin copying to. length – the number of elements to copy.

10 Array Copy This code produces the output
int[] a = {0, 1, 2, 3, 4, 5, 6}; int[] b = {1, 1, 1, 1, 1, 1, 1} System.arraycopy(a, 3, b, 1, 4); for(int i = 0; i < 7; i++) System.out.printf("b[%d] = %d ", i, b[i]); This code produces the output b[0] = 1 b[1] = 3 b[2] = 4 b[3] = 5 b[4] = 6 b[5] = 1 b[6] = 1 Four elements of array a, starting at index 3, were copied into array b, starting at index 1.

11 Array Demo The following is a program that demonstrates the array handling we have gone over. public class ArrayDemo { // A function that modifies an array static void arrayModifier(int[] p){ for (int i = 0; i < p.length; i++) p[i] = i; } public static void main(String[] args){ // default array declaration int[] x = new int[12]; System.out.println("Before function call."); for(int i = 0; i < 12; i++) System.out.printf("x[%d] = %d ", i, x[i]); System.out.printf("%n");

12 Array Demo // passing the array to a function arrayModifier(x); System.out.println("After function call,"); for(int i = 0; i < 12; i++) System.out.printf("x[%d] = %d ", i, x[i]); System.out.printf("%n"); // an array of characters char[] y; y = new char[5]; for(int i = 0; i < 5; i++) System.out.printf("y[%d] = %c ", i, y[i]); // array initializer int[] z = {12, 8, 7, 3, 4, 0, -1, 5, 14, 6}; // the length of the array System.out.printf("%nThe length of z is %d.%n", z.length);

13 Array Demo // copying an array int[] a = {0, 1, 2, 3, 4, 5, 6};
int[] b = {1, 1, 1, 1, 1, 1, 1}; System.out.println("Before the copy."); for(int i = 0; i < 7; i++) System.out.printf("b[%d] = %d ", i, b[i]); System.out.printf("%n"); System.arraycopy(a, 3, b, 1, 4); System.out.println("After the copy."); }

14 Interfaces One object oriented tool that Java provides is the ability to define an interface. An interface is a list of methods that a class must support. An example consider designing a car – cars have a fairly standard user interface (steering wheel, gas, brake, etc.) Different cars may implement the interface differently. What happens when you step on the gas? As long as a car supports the common interface we can drive the car. The methods of a class that supports an interface are like the controls on the car.

15 Interface Example Suppose we want to create an interface that could be used for bank accounts. There are several ways to interact with accounts but in our example we could do the following. Add money to the account (creditAccount) Withdraw money from the account (debitAccount) Print the balance (printBalance) If we want to support both credit card and checking accounts we should handle these actions differently. Debiting a credit card means you own more money. Debiting a checking account means you have less money.

16 Interface Example Here is an interface definition.
interface Account{ void debitAccount(double x); void creditAccount(double x); void printBalance(); } If this is stored in a separate .java file then the interface would need to be public. The interface lists methods that classes implementing it must possess. These classes could have additional methods not listed in the interface. The methods in the interface do not have bodies. They can be implemented in different ways in different classes.

17 Implementing an Interface
All the different account classes must declare that they implement the interface. Then the compiler will ensure that they have the required methods. If a class doesn’t have the necessarily methods that will be a syntax error. The methods can be implemented any way that is appropriate for that class. The classes can have other methods than the ones specified in the interface. Classes can also implement multiple interfaces.

18 Example Class The following is a class to implement a checking account. Notice that a checking account holds assets. class Checking implements Account { double assets; String name; Checking(double amount, String name){ assets = amount; this.name = name; }

19 Example Class The methods that implement the interface must be public.
public void debitAccount(double amount){ assets -= amount; } public void creditAccount(double amount){ assets += amount; public void printBalance(){ System.out.printf("You have $%.2f in %s", assets, name); The methods that implement the interface must be public.

20 Example Class A different class is used to implement credit card accounts. Notice that a credit account holds debts. class Credit implements Account { double debt; String name; Credit(double amount, String name){ debt = amount; this.name = name; }

21 Example Class public void debitAccount(double amount){ debt += amount; } public void creditAccount(double amount){ debt -= amount; public void printBalance(){ System.out.printf("You owe $%.2f to %s", debt, name);

22 Using Interfaced Classes
Because these classes support the same interface we can uses them interchangeably to the extent defined by the interface. For example we can declare an array that holds objects of type Account. All objects stored in the array need not be from the same class but would need to implement the Account interface. We can count on the objects supporting the interface. We can even create a for loop that runs through the entries, calling a common method.

23 Example Application Class
public class InterfaceDemo { public static void main(String[] args){ Account[] myAccounts = new Account[3]; myAccounts[0] = new Checking(1000, "AMSouth Checking"); myAccounts[1] = new Credit(0, "Visa"); myAccounts[2] = new Credit(0, "Mastercard"); myAccounts[0].debitAccount(100); myAccounts[1].debitAccount(32.95); myAccounts[0].creditAccount(2000); for (int i = 0; i < 3; i++){ myAccounts[i].printBalance(); System.out.println(); }

24 Events On a computer an event is something that happens that might need the computer’s attention. A key press on a keyboard. The arrival of a packet of information from the internet. A print job completes. A motor stops. etc. When the event occurs an interrupt is generated that stops the processor from doing its current job. At this point the processor can run a separate piece of code called an interrupt handler to deal with the situation. When it is done with the interrupt handler, is can go back to what it was doing before.

25 Handling an Event In Java, what happens when an event occurs is that the interrupt handler packages up information about what has occurred in an object, called an Event. Then the interrupt handler starts running some Java code called a listener that is assigned to that particular kind of event. We get to create our own listeners so that we can determine what happens when a certain event occurs. It is possible to create our own interrupt handlers and event classes as well, but this is usually done for us as part of an API. leJOS API Swing Android API etc.

26 Listeners and GUI Programming
When creating a graphical user interface (GUI) using event listeners is critical. It would be very difficult to write a loop that would check all the things that might happen. Click on various buttons. Click on various menus. Click in various windows. Type text. etc. Using a loop would also be very slow with many things to check. Finally, it would be expensive in processing power. The processor would spend all of its time checking instead of doing work.

27 Creating a Listener The leJOS API defines interfaces for the different types of listeners. KeyListener – listen for a certain key to be pressed or released. RegulatedMotorListener – listen for a particular motor to start or stop. FeatureListener – listen for a sensor to detect a particular feature.

28 Threads When a listener is activated, Java is actually creating a new thread to run the listener. A thread is like a second version of the the program running simultaneously. The two versions of the program share memory but they run independently. When the listener is done with its job, the new thread goes away.

29 KeyListener As an example let’s look at creating a KeyListener.
The KeyListener interface specifies two methods. void keyPressed(Key k) void keyReleased(Key k) If we want to implement the KeyListener interface, our class must have these two methods.

30 ButtonTest The following code creates a class to crease objects that listen and plays a series of sounds when the appropriate button is pressed. import lejos.hardware.*; class PlaySound implements KeyListener { public void keyPressed(Key k){ Sound.beepSequence(); } public void keyReleased(Key k) {} Notice that the keyReleased method doesn’t do anything, it just needs to satisfy the interface. Similarly, we don’t use the Key parameter, but it needs to be here.

31 ButtonTest The Key class could be used to determine information about the key that has been pressed. beepSequence is a method of the Sound class that plays a sequence of tones. Now let’s look at and application class that uses an object of the PlaySound class to listen to a key.

32 ButtonTest public class ButtonTest { public static void main(String[] args){ System.out.println("Press ENTER for a sound."); System.out.println("Press ESCAPE to quit."); Button.ENTER.addKeyListener(new PlaySound()); for(int i = 0; i < 1000; i++) System.out.println(i); Button.ESCAPE.waitForPressAndRelease(); }

33 ButtonTest This program adds an object of the PlaySound class as a listener for the ENTER key. The program then enters a loop that prints out the integers 0 to 1000. If you press a button while this is going on, it will play the tones and print numbers simultaneously. This shows that two threads can run concurrently. Each thread will be slower because of the limited resources of the EV3 brick.

34 Button Methods There are several other Button methods.
The buttons are identified by the following labels. ESCAPE LEFT RIGHT UP DOWN ENTER In the following code the wildcard <button> can be replaced with any of these labels. Button.<button>.waitForPressAndRelease() – waits for the button to be pressed and released, no return value. Button.<button>.isDown() – returns true if and only if the button is currently pressed. Button.setKeyClickTone(Button.<button>.getId(), frequency) – set the click tone of a button to a given frequency.

35 Homework Write a program that stores the first 25 Fibonacci numbers in an array and then prints them out. The Fibonacci numbers begin F(1) = 1 and F(2) = 1. After that the formula for the nth Fibonacci number is F(n) = F(n-1) + F(n-2)

36 Homework Examine the file PetCare.java. This file defines two classes and an interface. Create 3 different pet classes that implement the interface. You should have the pet types respond (print out) appropriately to the different foods and activities. The constructor for each pet should get its name as a parameter and the name should be stored in each pet object. There should be no numbers in your code; use the static fields provided in the given classes. Use the all of these classes to create a program where the user will be asked for 5 pet names and types. Store these pets in an array. Allow the user to indicate a pet index and what they want to do, feed the pet or do some type of activity. Pass this to the pet using the appropriate pet method and see how they respond.

37 Homework Write an EV3 program that invites the user to press any one of the 6 buttons on the EV3. The EV3 should exit the program if the ESCAPE key is pressed and should make a different sound for each of the other 5 keys. See the website and look at the Sound class in lejos.hardware for ideas about the sounds you could make. Use one or more KeyListener classes to implement your program. (You can have a KeyListener listen to more than one key.)


Download ppt "Lecture 6 Arrays and Interfaces."

Similar presentations


Ads by Google