You are on page 1of 80

Java I--Copyright © 2000 Tom Hunter

Chapter 6
Methods

Java I--Copyright © 2000 Tom Hunter


A Method Call
• A Method is invoked by a method call.
• The Syntax is as follows:

object.method(arguments);

spill
Java I--Copyright © 2000 Tom Hunter
A Method Call
• Usually, we start with an instance of an object.

• The object hands the method some information


(arguments) and asks that method to perform a task
based on that information.

• When the the task is done, the method returns information


back to the object that called it.

return =
object.method(arguments);
Java I--Copyright © 2000 Tom Hunter
A Method Call
• Teacher.asksStudent( help );

Java I--Copyright © 2000 Tom Hunter


A Method Call
• Teacher.asksStudent( help );

• The OBJECT (Teacher) does not need to know how the


method (student) accomplished the request.

• Maybe the men’s room was empty and the student had
to go get towels from the ladies room.

Java I--Copyright © 2000 Tom Hunter


A Method Call

• Maybe the custodian was filling up the dispenser, and


he had to ask the custodian to give him some towels.

• I--the Object--don’t need to know how he accomplished


the method.

• I made a request and got back results.

Java I--Copyright © 2000 Tom Hunter


A Method Call
• Teacher.asksStudent( help );

• When we’re writing software, one object is independent


of another.

• How any object implements its own methods is


hidden from the outside world.

• That way, once your method works,


nobody can mess it up.

Java I--Copyright © 2000 Tom Hunter


A Method Call
• Hiding the implementation of a method
promotes good software engineering.

• If you can’t change how an object performs its


methods, then you can’t introduce errors.

• You have to live with the way it works now.

Java I--Copyright © 2000 Tom Hunter


A Method Call
• A Method can receive as many arguments as you wish.

• A Method can only return ONE thing.

method

Java I--Copyright © 2000 Tom Hunter


A Method Call
• A Method Always Receives A Copy Of Its
Arguments

• Since a Method Only Receives a duplicate, it can

NEVER change the original copy

of the parameter it received.

Java I--Copyright © 2000 Tom Hunter


import java.awt.Container;
import javax.swing.*; Notice this syntax:
We are inside method init(),
public class SquareInt extends JApplet
{ yet we’re calling to another
public void init() method square() without
{
String output = ""; referring to an object.
JTextArea oArea = new JTextArea( 10, 20 in
“Methods );a class definition
Container c = getContentPane();
c.add( oArea ); are allowed to invoke all
int result;
for( int x = 1; x <= 10; x++ other
) methods in the same class
{ this way.”
result = square( x );
output += ”Square of " + xInherited
+ methods can
" is " + result + "\n";
} be called this same
outputArea.setText( output );
} way.

public int square( int y )


{
return y * y;
}
}

Java I--Copyright © 2000 Tom Hunter


import java.awt.Container;
import javax.swing.*;
Result
public class SquareInt extends JApplet ?
{
public void init()
{ x
String output = "";
JTextArea oArea = new JTextArea( 10, 20 ); 2
Container c = getContentPane();
c.add( oArea );
int result;
for( int x = 2; x <= 10; x++ )
{
result = square( x );
output += ”Square of " + x +
" is " + result + "\n";
} y
outputArea.setText( output );
} 2

public int square( int y )


{
return y * y;
}
}

Java I--Copyright © 2000 Tom Hunter


import java.awt.Container;
import javax.swing.*;
Result
public class SquareInt extends JApplet
{ 4?
public void init()
{
String output = "";
JTextArea oArea = new JTextArea( 10, 20 ); x
Container c = getContentPane();
c.add( oArea ); 2
int result;
for( int x = 1; x <= 10; x++ )
{
result = square( x );
output += ”Square of " + x +
" is " + result + "\n";
} y
outputArea.setText( output );
} 2

public int square( int y )


{
return y * y;
}
}

Java I--Copyright © 2000 Tom Hunter


How Do We Build A
GUI Screen?
A Container is the building block...

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()
import java.awt.Container;
import javax.swing.*;

public class SquareInt extends JApplet


{
public void init()
{

JTextArea oArea = new JTextArea( 10, 20 );


Container c = getContentPane();
c.add( oArea );

• What is a Container?
• What is happening in these two statements?

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()

• A Container is something that can


contain other objects.

• For example, JApplet is a container


that can hold buttons, labels and other
things that are also themselves objects.

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()
• Swing gives us three top-level Container classes:
JApplet,
JFrame and
JDialog

• As you see here, the Frame (not a JFrame)


is the largest unit.
Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
• Included within a
Frame is a
content pane.

• You can’t just drop a button or a label on a Frame--


you have to put any smaller component--what we call
a button or a label--on the content pane first.
Java I--Copyright © 2000 Tom Hunter
Frame

“contentPane”

Button Label
Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
Container c = getContentPane();

• Let’s do some research:

• getContentPane() is a method of the


JApplet class.

• getContentPane() is a method of the


JFrame class.

• getContentPane() is a method of the


JDialog class.
Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
Container c = getContentPane();

• When this method [getContentPane() ]


executes, it returns an object of type
Container.

JApplet

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()
Container c = getContentPane();

•Therefore, it makes sense that we could


declare a Container variable c and use
getContentPane() to initialize it.

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()
Container c = getContentPane();

• Every JApplet inherits a Container.

Java I--Copyright © 2000 Tom Hunter


import javax.swing.*;
import java.awt.Container;
public class TestApp extends JApplet
{
public void init()
{
JTextArea tst = new JTextArea( 10, 5 );
tst.setText( " Hello " );

Container c = getContentPane();
c.add( tst );
} Container c
}
Content Pane
JTextArea tst

Java I--Copyright © 2000 Tom Hunter


Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
Container c = getContentPane();

• A frame is the main window.


• A frame is the top-level
container. It exists mainly
to give us a place for
other swing components
to paint themselves.

• But you can never place any objects directly on a frame.


Instead, you place them on the content pane.

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()
Container c = getContentPane();

• Applets and Dialogs can serve the same


purpose a frame can--as the main window
other things paint
themselves on.
Note:
Applet != JApplet
Dialog != JDialog
Frame != JFrame

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()
Container c = getContentPane();

• A button and label are the atomic


components. The parts don’t get any smaller
than buttons and labels.
They are the end of the
line. No other object is
ever placed
on these.

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()
Container c = getContentPane();

• A panel is the middle container. A panel


gives us a place to put buttons and labels.

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()
Container c = getContentPane();

• Consider this window:


It starts with a JFrame,
then gets the content
{
pane in the middle,
layers a JPanel on that,
and finally lays on the
JButton and JLabel.

d
Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
Container c = getContentPane();

• A JPanel object is a simple


container object with no fancy
additions.

d
Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
Container c = getContentPane();

• A pane is the middle


area used for building.

• A split pane

• A layered pane • A tabbed pane


Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
Container c = getContentPane();

• Note: to view the


“containment hierarchy”
of any frame or dialog,
click its border to select
it, then press:
Ctrl-Shift-1. A list of the
containment hierarchy
will be printed on the
console. Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
Container c = getContentPane();

• So, what is a Container?

• Every top-level container contains an


intermediate container known as a
content pane.
Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
Container c = getContentPane();

• The content pane contains all of the visible


components in a window’s GUI.
• Only the menu bar is not included within the
content pane.
• So, the statement above
means: “Give me the
visible portion of my
applet. I want to put
something there.”
Java I--Copyright © 2000 Tom Hunter
Method getContentPane()
JTextArea oArea = new JTextArea( 10, 20 );
Container c = getContentPane();
c.add( oArea );

• So, I execute the JApplet’s method


“getContentPane()” and it returns to me
a container object c.

Java I--Copyright © 2000 Tom Hunter


Method getContentPane()
JTextArea oArea = new JTextArea( 10, 20 );
Container c = getContentPane();
c.add( oArea );

• Into this Container


object, I add anything
that is a component.
In this case, I add the
component JTextArea.

Java I--Copyright © 2000 Tom Hunter


You will only
remember this
process when you
are practicing it...

Java I--Copyright © 2000 Tom Hunter


Math Class Methods
• Found in java.lang.Math
• Automatically imported.

Math.sqrt( 900.0 )

30.0 = Math.sqrt( 900.0 )

Type double
Java I--Copyright © 2000 Tom Hunter
Math Class Methods

• Work from the Inside Out


• First Math.sqrt() is performed.

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.
Java I--Copyright © 2000 Tom Hunter
Math Class Methods

• You can never make an instance of the Math


library.
• For the sake of Contrast: Making an instance of the
Graphics class. This instance
Graphics g; is called “g”.

g.drawString( “Calling A Method” );

Now, this instance will call its method drawString


Java I--Copyright © 2000 Tom Hunter
Math Class Methods

• You can’t create a Math instance.

Math m;

Java I--Copyright © 2000 Tom Hunter


Math Class Methods
• All the methods in the Math class are declared
static--which means the class can’t be
instantiated.

• When we declare a method static, it means


only the class itself can ever call the method. No
extra instances of it can be made.
Java I--Copyright © 2000 Tom Hunter
Math Class Methods
• 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.
Java I--Copyright © 2000 Tom Hunter
Math Class Methods
• 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:
Graphics g

g.drawString

Java I--Copyright © 2000 Tom Hunter


Math Class Methods
• 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


can’t be instantiated.

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.

Java I--Copyright © 2000 Tom Hunter


More About Methods

• In this example, all three variables are local. The


variables x and y declared as parameters in the header,
and the variable sum declared in the body of the method.

public double sum( double x, double y)


{
double sum = 0;

sum = x + y;
return sum;
}

Java I--Copyright © 2000 Tom Hunter


Methods: Coercion of
Arguments
• What would happen if--when we called this method--we
passed it integers, rather than the doubles it expects?

public double sum( double x, double y)


{
double sum = 0;

sum = x + y;
return sum;
}

Java I--Copyright © 2000 Tom Hunter


Methods: Coercion of Arguments

• If it was able to, the compiler would


attempt to convert or “coerce” the
arguments into the right type.

• If I passed it an integer and it expected a


double, the conversion would be no
problem--converting an integer into a
double doesn’t lose any information.

Java I--Copyright © 2000 Tom Hunter


Methods: Coercion of Arguments

• However, if I passed it a double and it was


expecting an integer, the conversion from
double to integer WOULD lose information,
so the compiler would complain.

• The compiler would complain unless I used


an explicit cast operator to force the
argument into the right type.

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
automatic.
• Automatic 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.

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

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.


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

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.

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.

Java I--Copyright © 2000 Tom Hunter


Event Delegation Model
Event Sources
transmit
ActionEvent
objects
to Event Listener(s).

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.”
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 );

Java I--Copyright © 2000 Tom Hunter


Event Delegation Model

MyPanel panel = new MyPanel();


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

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

Java I--Copyright © 2000 Tom Hunter


Event Delegation Model

MyPanel panel = new MyPanel();


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

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

Java I--Copyright © 2000 Tom Hunter


Event Delegation Model

MyPanel panel = new MyPanel();


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

• To implement the ActionListener interface, the listener


class must have a method called

actionPerformed( ActionEvent e )

that receives an ActionEvent object as a parameter.

Java I--Copyright © 2000 Tom Hunter


Event Delegation Model
public class MyPanel extends JPanel
implement ActionListener
{
public void actionPerformed( ActionEvent e )
{
// appropriate code to react to event
// goes here.
}
}

• Whenever the user clicks the button, the JButton


object creates an ActionEvent object and calls
panel.actionPerformed, passing that event
object.

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.

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

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...
}
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.
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;
First, to respond to events, we
int gameStatus = CONTINUE;

must
// GUI components.
JLabel
import
die1Label,
the
event class API:
die2Label,
sumLabel,
java.awt.event.*;
pointLabel;

JTextField firstDie,
secondDie,
sum,
point;

JButton roll;
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;
This is the first time we have seen a class that
“implements” another
// GUI components.
JLabel
class.
die1Label,
This is called an
interface. You see,die2Label,
although we are directly
sumLabel,
inheriting from the class JApplet, we are
pointLabel;
getting some functions
JTextField
through the interface
firstDie,
from the class ActionListener.
secondDie, We will
sum,
learn more about
point; interfaces later.

JButton roll;

Java I--Copyright © 2000 Tom Hunter


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Here are 3 different kinds of GUI
public class Craps extends JApplet implements ActionListener
{ “components.” Remember, a
final int WON = 0, LOST = 1, CONTINUE = 2;
component is something we place on
boolean firstRoll = true;
int sumOfDice = 0; the content pane.
int myPoint = 0;
int gameStatus = CONTINUE;

// GUI components.
JLabel die1Label,
die2Label,
sumLabel,
pointLabel;

JTextField firstDie,
secondDie,
sum,
point;

JButton roll;

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;

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;

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;

Java I--Copyright © 2000 Tom Hunter


Java I--Copyright © 2000 Tom Hunter
Java I--Copyright © 2000 Tom Hunter
Java I--Copyright © 2000 Tom Hunter
Java I--Copyright © 2000 Tom Hunter

You might also like