Methods

  • 371 views
Uploaded on

 

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
371
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
7
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters

Transcript

  • 1. Java I--Copyright © 2000 Tom Hunter
  • 2. Java I--Copyright © 2000 Tom Hunter Chapter 6 Methods
  • 3. Java I--Copyright © 2000 Tom Hunter • A Method is invoked by a method call. • The Syntax is as follows: object.method(arguments); A Method Call spill
  • 4. Java I--Copyright © 2000 Tom Hunter • 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); A Method Call
  • 5. Java I--Copyright © 2000 Tom Hunter • Teacher.asksStudent( help ); A Method Call
  • 6. Java I--Copyright © 2000 Tom Hunter • 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. A Method Call
  • 7. Java I--Copyright © 2000 Tom Hunter • 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. A Method Call
  • 8. Java I--Copyright © 2000 Tom Hunter • 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. A Method Call
  • 9. Java I--Copyright © 2000 Tom Hunter • 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. A Method Call
  • 10. Java I--Copyright © 2000 Tom Hunter • A Method can receive as many arguments as you wish. • A Method can only return ONE thing. A Method Call method
  • 11. Java I--Copyright © 2000 Tom Hunter • 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. A Method Call
  • 12. Java I--Copyright © 2000 Tom Hunter import java.awt.Container; import javax.swing.*; public class SquareInt extends JApplet { public void init() { String output = ""; JTextArea oArea = new JTextArea( 10, 20 ); Container c = getContentPane(); c.add( oArea ); int result; for( int x = 1; x <= 10; x++ ) { result = square( x ); output += ”Square of " + x + " is " + result + "n"; } outputArea.setText( output ); } public int square( int y ) { return y * y; } } Notice this syntax: We are inside method init(), yet we’re calling to another method square() without referring to an object. “Methods in a class definition are allowed to invoke all other methods in the same class this way.” Inherited methods can be called this same way.
  • 13. Java I--Copyright © 2000 Tom Hunter import java.awt.Container; import javax.swing.*; public class SquareInt extends JApplet { public void init() { String output = ""; JTextArea oArea = new JTextArea( 10, 20 ); 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"; } outputArea.setText( output ); } public int square( int y ) { return y * y; } } x 2 Result ? y 2
  • 14. Java I--Copyright © 2000 Tom Hunter Result ? import java.awt.Container; import javax.swing.*; public class SquareInt extends JApplet { public void init() { String output = ""; JTextArea oArea = new JTextArea( 10, 20 ); Container c = getContentPane(); c.add( oArea ); int result; for( int x = 1; x <= 10; x++ ) { result = square( x ); output += ”Square of " + x + " is " + result + "n"; } outputArea.setText( output ); } public int square( int y ) { return y * y; } } Result 4 x 2 y 2
  • 15. Java I--Copyright © 2000 Tom Hunter How Do We Build A GUI Screen? A Container is the building block...
  • 16. 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?
  • 17. 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.
  • 18. 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.
  • 19. Java I--Copyright © 2000 Tom Hunter • 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. Method getContentPane()
  • 20. Java I--Copyright © 2000 Tom Hunter Frame “contentPane” Button Label
  • 21. 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.
  • 22. Java I--Copyright © 2000 Tom Hunter Method getContentPane() Container c = getContentPane(); • When this method [getContentPane() ] executes, it returns an object of type Container. JApplet
  • 23. 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.
  • 24. Java I--Copyright © 2000 Tom Hunter Method getContentPane() Container c = getContentPane(); • Every JApplet inherits a Container.
  • 25. 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
  • 26. Java I--Copyright © 2000 Tom Hunter
  • 27. 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.
  • 28. 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
  • 29. 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.
  • 30. 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.
  • 31. 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 {
  • 32. Java I--Copyright © 2000 Tom Hunter Method getContentPane() Container c = getContentPane(); • A JPanel object is a simple container object with no fancy additions. d
  • 33. Java I--Copyright © 2000 Tom Hunter Method getContentPane() Container c = getContentPane(); • A pane is the middle area used for building. • A layered pane • A split pane • A tabbed pane
  • 34. 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.
  • 35. 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.
  • 36. 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.”
  • 37. 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.
  • 38. 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.
  • 39. Java I--Copyright © 2000 Tom Hunter You will only remember this process when you are practicing it...
  • 40. Java I--Copyright © 2000 Tom Hunter • Found in java.lang.Math • Automatically imported. Math Class Methods Math.sqrt( 900.0 ) 30.0 = Math.sqrt( 900.0 ) Type double
  • 41. 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.
  • 42. Java I--Copyright © 2000 Tom Hunter • You can never make an instance of the Math library. • For the sake of Contrast: Graphics g; g.drawString( “Calling A Method” ); Math Class Methods Making an instance of the Graphics class. This instance is called “g”. Now, this instance will call its method drawString
  • 43. Java I--Copyright © 2000 Tom Hunter • You can’t create a Math instance. Math m; Math Class Methods
  • 44. Java I--Copyright © 2000 Tom Hunter • All the methods in the Math class are declared static--which means the class can’t be instantiated. Math Class Methods • 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.
  • 45. 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
  • 46. 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: Graphics g g.drawString Math Class Methods
  • 47. 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 can’t be instantiated. Math Class Methods
  • 48. 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.
  • 49. 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 header, and the variable sum declared in the body of the method.
  • 50. Java I--Copyright © 2000 Tom Hunter Methods: Coercion of Arguments public double sum( double x, double y) { double sum = 0; sum = x + y; return sum; } • What would happen if--when we called this method--we passed it integers, rather than the doubles it expects?
  • 51. 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.
  • 52. 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.
  • 53. 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.
  • 54. 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
  • 55. 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.
  • 56. 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.
  • 57. 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.
  • 58. 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.
  • 59. 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.
  • 60. Java I--Copyright © 2000 Tom Hunter Event Delegation Model Event Sources transmit ActionEvent objects to Event Listener(s).
  • 61. 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.”
  • 62. 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 );
  • 63. 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 );
  • 64. 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 );
  • 65. 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 );
  • 66. 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 JPanel implement ActionListener { public void actionPerformed( ActionEvent e ) { // appropriate code to react to event // goes here. } }
  • 67. 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.
  • 68. 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 ) ... }
  • 69. 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... }
  • 70. 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.
  • 71. 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 the event class API: java.awt.event.*;
  • 72. 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.
  • 73. 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.
  • 74. 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;
  • 75. 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;
  • 76. 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;
  • 77. Java I--Copyright © 2000 Tom Hunter
  • 78. Java I--Copyright © 2000 Tom Hunter
  • 79. Java I--Copyright © 2000 Tom Hunter
  • 80. Java I--Copyright © 2000 Tom Hunter