java i lecture_7

64
Java I--Copyright © 2000 Tom Hunter

Upload: mithun-dp

Post on 26-May-2015

74 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Page 2: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Chapter 6

Methods: Part II

Page 3: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

• Found in java.lang.Math

• Automatically imported.

• sqrt() is a “static” method.

Math Class Methods

Math.sqrt( 900.0 )

30.0 = Math.sqrt( 900.0 )

Type double

Page 4: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

• Work from the Inside Out

• First Math.sqrt() is performed.

Math Class Methods

System.out.println( Math.sqrt( 900.0 ) );

System.out.println( 30.0 );

• The return value of Math.sqrt is the argument for the println method.

Page 5: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

• You can never make an instance of the Math object—because it was declared final.

• For the sake of Contrast:

Container c;

c.add( “Calling A Method” );

Math Class Methods

Making an instance of the Container class. This instance

is called “c”. “c” is the “reference” to this object.

Now, this instance will call its method add()

Page 6: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

• You can’t create a Math instance.

Math m;

Math Class Methods

Page 7: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

• All the methods in the Math class are declared

static--which means they belong to the class.

Math Class Methods

• When we declare a method static, it means we don’t need to instantiate the class to call the method.

Page 8: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

• Review all the ways to call a method:

A Method Name All by itself, such as

d = square( x );

• We don’t refer to the object where this method originates.

Math Class Methods

Page 9: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

• Review all the ways to call a method:

A Reference to an object we have instantiated

followed by the dot . operator and the method name:

MyClass w

w.myMethod()

Math Class Methods

Page 10: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

• Review all the ways to call a method:

A class name followed by a method:

Integer.parseInt()

This is only used for static methods that belong to the class.

Math Class Methods

Page 11: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

More About Methods• Recall the all variables declared inside a method are local variables.

• Local variables must be initialized.

• They live only while the method is being executed.

• Local variables vanish after the method is done.

Page 12: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

More About Methods

public double sum( double x, double y){

double sum = 0;

sum = x + y;return sum;

}

• In this example, all three variables are local. The variables x and y declared as parameters in the method signature, and the variable sum declared in the body of the method.

Page 13: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Methods: Duration of Identifiers• The duration of an identifier is the lifetime of the identifier.

• Identifiers declared locally in a method are called local variable. (They are also known as automatic variable).

• Automatic (local) variables exist only while the block they are declared in executes.

• Static variables exist from the time the class that defines them is loaded into memory until the program terminates.

Page 14: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Methods: Scope Rules• The scope for an identifier is the portion of the program in which the identifier can be referenced.

• The scopes for an identifier are:

• class

• block

• method

Page 15: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Method Overloading• Method overloading allows a method name to be re-used.

• To overload a method--or to create another version of a method that already exists--the argument lists for the methods must differ in:

• number of arguments

• type of arguments

• order of arguments

• The return type of the method is NOT considered.

Page 16: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation

Model

Page 17: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Unlike many other languages--such as Visual Basic--when the Java programmer wishes to program responses to an event--such as the enter key being pressed, the event must be entirely programmed.

Page 18: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Consider this analogy to the event model:

> Fred decides he wants a bodyguard.

> Somebody punches Fred--that’s a problem.

> Vinnie--the bodyguard--notices Fred was punched.

> Vinnie reacts to the problem.

Page 19: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• The same thing with specifics attached:

> A Button decides it wants an ActionListener.

> A Button is pressed--an event happens:

> The ActionListener notices the Button was pressed.

> The Listener reacts to the event.

Page 20: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Fully described in Java Terms

> A Button adds an ActionListener.

> A Button is pressed--an event happens:

> The method actionPerformed is executed,

receiving an ActionEvent object.

> The Listener reacts to the event.

Page 21: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

Event Sources

transmit

ActionEvent

objects

to Event Listener(s).

Page 22: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model: Summarized

• An event source is an object that can register listener* objects and send those listeners event objects.

• In practice, the event source can send out event objects to all registered listeners when that event occurs.

• The listener object(s) will then use the details in the event object to decide how to react to the event.

* A “Listener Object” [an instance of a class] implements a special interface called a “listener interface.”

Page 23: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• When you ask the listener object to pay attention to your event source, that is called registering the listener object with the source object.

• You do that with the following lines of code:

eventSourceObject.addEventListener( eventListenerObject );

Page 24: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Now, the panel object is notified whenever an “action event” occurs in the button.

• When you click on a button, the panel object hears about it.

MyPanel panel = new MyPanel(); JButton button = new JButton( “Clear” ); button.addActionListener( panel );

Page 25: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Code like this requires that the class the panel comes from to implement the appropriate interface.

• In this case, class MyPanel must implement the ActionListener interface.

MyPanel panel = new MyPanel(); JButton button = new JButton( “Clear” ); button.addActionListener( panel );

Page 26: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• To implement the ActionListener interface, the listener class must have a method called

actionPerformed( actionPerformed( ActionEventActionEvent ee ) )

that receives an ActionEvent object as a parameter.

MyPanel panel = new MyPanel(); JButton button = new JButton( “Clear” ); button.addActionListener( panel );

Page 27: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Whenever the user clicks the button, the JButton object creates an ActionEvent object and calls panel.actionPerformed, passing that event object.

public class MyPanel extends JPanelimplement ActionListener

{ public void actionPerformed( ActionEvent e ) { // appropriate code to react to event

// goes here. }}

Page 28: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model: Which Button Was Clicked?

• A closer look at the object that is passed, the ActionEvent object:

• The method getSource() will tell us which object created and sent the ActionEvent object.

Page 29: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model: Which Button Was Clicked?

• Responding to a button:

We start with a panel and some buttons on it.

• A listener object ( namely, the panel itself ) registers itself with the buttons so that it can listen to them.

public void actionPerformed( ActionEvent e )

{

if ( e.getSource() == button )

...

}

Page 30: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Every event handler requires 3 bits of code:

1. Code that says the class implements a listener interface:

public class MyClass implements ActionListener

2.Code that registers a listener on one or more components.

someComponent.addActionListener( MyClass ); 3.Code that implements the methods in the listener interface.

public void actionPerformed(ActionEvent e){ ...//code that reacts to the action...}

Page 31: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model: Another Example

• In code, this is how you react to an event:

JButton roll = new JButton( “Roll Dice” );

roll.addActionListener( this );

// call method play when button is pressed.

Public void actionPerformed( ActionEvent e )

{

do something

}

• When the JButton roll is clicked, the method actionPerformed receives an ActionEvent object that tells it the details of the event.

Page 32: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;

import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

Page 33: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;

import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

First, to respond to events, we must import theevent class API:

java.awt.event.*;

Page 34: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

Page 35: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

This is the first time we have seen a class that “implements” another class. This is called an interface. You see, although we are directly inheriting from the class JApplet, we are getting some functions through the interface from the class ActionListener. We will

learn more about interfaces later.

Page 36: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

Page 37: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

Here are 3 different kinds of GUI “components.” Remember, a

component is something we place on the content pane.

Page 38: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

// Setup graphical user interface componentspublic void init(){

Container c = getContentPane();c.setLayout(new FlowLayout() );

die1Label = new JLabel( "Die 1" );c.add( die1Label );

firstDie = new JTextField( 10 );firstDie.setEditable( true );c.add( firstDie );

roll = new JButton( "Roll Dice" );roll.addActionListener( this );c.add( roll );

} // end of method init()

Page 39: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

// Setup graphical user interface componentspublic void init(){

Container c = getContentPane();c.setLayout(new FlowLayout() );

die1Label = new JLabel( "Die 1" );c.add( die1Label );

firstDie = new JTextField( 10 );firstDie.setEditable( true );c.add( firstDie );

roll = new JButton( "Roll Dice" );roll.addActionListener( this );c.add( roll );

} // end of method init()

c is a Container object that came from the Content Pane. Here, we are setting the Layout, or how the objects get stacked on the page.

There are many different choices for layouts. We will discuss them

later.

Page 40: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

// Setup graphical user interface componentspublic void init(){

Container c = getContentPane();c.setLayout(new FlowLayout() );

die1Label = new JLabel( "Die 1" );c.add( die1Label );

firstDie = new JTextField( 10 );firstDie.setEditable( true );c.add( firstDie );

roll = new JButton( "Roll Dice" );roll.addActionListener( this );c.add( roll );

} // end of method init()

Page 41: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

// Setup graphical user interface componentspublic void init(){

Container c = getContentPane();c.setLayout(new FlowLayout() );

die1Label = new JLabel( "Die 1" );c.add( die1Label );

firstDie = new JTextField( 10 );firstDie.setEditable( true );c.add( firstDie );

roll = new JButton( "Roll Dice" );roll.addActionListener( this );c.add( roll );

} // end of method init()

Earlier, we declared these JLabels and now we’re defining them. Then, we see how the Container c is

using its method “add” to add the JLabels object die1Label to its content pane.

Page 42: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

// Setup graphical user interface componentspublic void init(){

Container c = getContentPane();c.setLayout(new FlowLayout() );

die1Label = new JLabel( "Die 1" );c.add( die1Label );

firstDie = new JTextField( 10 );firstDie.setEditable( true );c.add( firstDie );

roll = new JButton( "Roll Dice" );roll.addActionListener( this );c.add( roll );

} // end of method init()

Page 43: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

// Setup graphical user interface componentspublic void init(){

Container c = getContentPane();c.setLayout(new FlowLayout() );

die1Label = new JLabel( "Die 1" );c.add( die1Label );

firstDie = new JTextField( 10 );firstDie.setEditable( true );c.add( firstDie );

roll = new JButton( "Roll Dice" );roll.addActionListener( this );c.add( roll );

} // end of method init()

Below, you see how we have defined a new JButton called “roll”. Then, we register an Action Listener on the button

roll. We want our same JApplet--the one we are inside of now--to listen to for the events. To say that, we use the

“this” reference below. It means “this” JApplet will listen for events that happen to the JButton “roll”. This is called

“registering an Action Listener”.

Page 44: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

// call method play when button is pressed.public void actionPerformed( ActionEvent e ){ play();

}

• So, when an event happens to our button--because of the ActionListener--the following method is performed. It receives an ActionEvent object.

• In our example, this method just calls another method, play()

Page 45: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

// process one roll of the dice.public void play(){ if( firstRoll )

{ sumOfDice = rollDice(); switch( sumOfDice )

{ case 7: case 11: gameStatus = WON; point.setText( "" ); break; case 2: case 3: case 12: gameStatus = LOST; point.setText( "" ); break;} // end of switch

} //end of true if block else

{ sumOfDice = rollDice(); if( sumOfDice == myPoint )

gameStatus = WON; else

This method decides what to do when the event happens.

Page 46: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Interfaces• When we said our program:

implements ActionListener

it was implementing a thing called an interface.

If you want to implement the interface ActionListener, it means that you must define a method called:

public void actionPerformed( ActionEvent e )

in your class. (More about Interfaces later…)

Page 47: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Layout Managers• Recall that you use the getContentPane() method as a starting point when you want to place components on a GUI.

• After that, how are your GUI components organized on the window?

• The Layout Manager controls how this happens.

A Layout Manager determines the position and size of every GUI component attached to a Container.

Page 48: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Layout Managers

• Flow Layout is the most basic. It places the objects one after another, top to bottom, left to right, on the Container.

Page 49: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Layout Managers

• This is the same Applet as on the previous slide. It has only be resized to a different shape.

Page 50: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Recursion• For any programming problem, there are usually two alternative ways to solve it:

--iteration and

--recursion

• Iteration means repeating the same thing a certain number of times until the solution is achieved.

• Recursion means having a method call itself. Or rather, it’s better to think that it calls another copy of itself.

Page 51: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Recursion

• If we choose to call a method recursively, it means we are calling it numerous times until we arrive at the solution.

• Ironically, a recursive method can only actually solve the simplest “base” case.

• The other, more complex cases wait until the simplest base case is solved and then it works from the inside out until all the cases are solved.

Page 52: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

Recursion Example: The Fibonacci Series

• This is a Fibonacci series:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...

• It makes the next number in the sequence by adding together the previous two numbers.

Page 53: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class FibonacciTest extends JApplet implements ActionListener{

JLabel numLabel,resultLabel;

JTextField num,result;

public void init(){

Container c = getContentPane();c.setLayout( new FlowLayout() );

numLabel = new JLabel( "Enter and Integer and press Enter" );c.add( numLabel );

num = new JTextField( 10 ); // creates a new JTextField with 10 columnsnum.addActionListener( this );// makes "this" Applet listen for events.c.add( num );

resultLabel = new JLabel( "Fibonacci value is " );c.add( resultLabel );

result = new JTextField( 15 );result.setEditable( false );c.add( result );

} // end of method init()

Page 54: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

public void actionPerformed( ActionEvent e ){ long number,

fibonacciValue;

number = Long.parseLong( num.getText() ); showStatus( "Calculating..." ); // status area of Applet fibonacciValue = fibonacci( number ); showStatus( "Done" ); result.setText( Long.toString( fibonacciValue ) );} // end of method actionPerformed()

// Recursive definition of method Fibonaccipublic long fibonacci( long n ){

if( n == 0 || n == 1 ) // base case { return n;

} else

{ return fibonacci( n - 1 ) + fibonacci( n - 2 ); }

} // end of method fibonacci()} // end of class FibonacciTest

Page 55: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

public long fibonacci( long n ){ if( n == 0 || n == 1 ) // base case { return n;

} else

{ return fibonacci( n - 1 ) + fibonacci( n - 2 ); }

}

• This method is called repeatedly until it reaches the base case, then the previous copies of the method--that had been waiting for the else to finish--complete their execution from the inside out.

Page 56: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

JApplet’s Methods• Earlier I said that JApplet has three methods:

init()

start()

paint()• These are always guaranteed to be performed.

• If you override these methods--exactly override their signatures--they will execute automatically.

• If you do not exactly copy their signatures, then your override will not automatically be executed.

Page 57: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

JApplet’s Methods

• In addition to these are several others:

init()

start()

paint()

stop()

destroy()• As they are inherited, these members are guaranteed to be called--but still none of them contain any code.

• They are all empty, and only contain code when you override them and add some.

Page 58: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

JApplet’s Methods

init()

• This method is called when the Applet is first created, to perform first-time initialization of the applet.

Page 59: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

JApplet’s Methods

start()

• This method is called every time the applet moves into site on the web browser to permit the applet to start up its normal operations ( especially those that are shut off by stop() )

• This is called automatically after init().

Page 60: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

JApplet’s Methods

paint()

• This method does not even come from JApplet or Applet. It is inherited down the hierarchy from the base class Component, up three levels of the inheritance tree.

• This method is called automatically after init() and start() have been called.

• If you ever resize an applet, first method update() is called and update calls paint()

Page 61: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

JApplet’s Methods

paint()

• If your applet ever gets covered up, then when it returns to the top it needs to restore itself. Method start() is automatically called and then method update() (which comes from class Component) and finally paint().

• So, to recap, anytime you resize your applet, you are firing method update(), which in turn fires method paint().

Page 62: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

JApplet’s Methods

paint()

• When update() calls paint(), update() sends paint() a handle to a Graphics object that represents the surface on which you can paint.

Page 63: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

JApplet’s Methods

stop()

• This method is called whenever the applet is hidden from view by going behind another window or being minimized. This allows the web browser to quit wasting CPU cycles on anything the applet is doing.

• Right before the method destroy() is called, this stop() is first called to halt the applet’s processing.

Page 64: Java i lecture_7

Java I--Copyright © 2000 Tom Hunter

JApplet’s Methods

destroy()

• This method is called when the applet is being unloaded from the web page.

• This method permits the final release of memory resources when the applet is no longer being used.