Your SlideShare is downloading. ×
0
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Java i lecture_7
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Java i lecture_7

55

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
55
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
1
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 HunterChapter 6Methods: Part II
    • 3. Java I--Copyright © 2000 Tom Hunter• Found in java.lang.Math• Automatically imported.• sqrt() is a “static” method.Math Class MethodsMath.sqrt( 900.0 )30.0 = Math.sqrt( 900.0 )Type double
    • 4. Java I--Copyright © 2000 Tom Hunter• Work from the Inside Out• First Math.sqrt() is performed.Math Class MethodsSystem.out.println( Math.sqrt( 900.0 ) );System.out.println( 30.0 );• The return value of Math.sqrt is the argument for theprintln method.
    • 5. Java I--Copyright © 2000 Tom Hunter• You can never make an instance of the Mathobject—because it was declared final.• For the sake of Contrast:Container c;c.add( “Calling A Method” );Math Class MethodsMaking an instance of theContainer class. This instanceis called “c”. “c” is the“reference” to this object.Now, this instance will call its method add()
    • 6. Java I--Copyright © 2000 Tom Hunter• You can’t create a Math instance.Math m;Math Class Methods
    • 7. Java I--Copyright © 2000 Tom Hunter• All the methods in the Math class are declaredstatic--which means they belong to the class.Math Class Methods• When we declare a method static, it means wedon’t need to instantiate the class to call themethod.
    • 8. Java I--Copyright © 2000 Tom Hunter• Review all the ways to call a method:A Method Name All by itself, such asd = square( x );• We don’t refer to the object where this methodoriginates.Math Class Methods
    • 9. Java I--Copyright © 2000 Tom Hunter• Review all the ways to call a method:A Reference to an object we have instantiatedfollowed by the dot . operator and the methodname:MyClass ww.myMethod()Math Class Methods
    • 10. 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 thatbelong to the class.Math Class Methods
    • 11. Java I--Copyright © 2000 Tom HunterMore About Methods• Recall the all variables declared inside a method arelocal variables.• Local variables must be initialized.• They live only while the method is being executed.• Local variables vanish after the method is done.
    • 12. Java I--Copyright © 2000 Tom HunterMore About Methodspublic double sum( double x, double y){double sum = 0;sum = x + y;return sum;}• In this example, all three variables are local. Thevariables x and y declared as parameters in the methodsignature, and the variable sum declared in the body ofthe method.
    • 13. Java I--Copyright © 2000 Tom HunterMethods: Duration of Identifiers• The duration of an identifier is the lifetime of theidentifier.• Identifiers declared locally in a method are called localvariable. (They are also known as automatic variable).• Automatic (local) variables exist only while the blockthey are declared in executes.• Static variables exist from the time the class that definesthem is loaded into memory until the program terminates.
    • 14. Java I--Copyright © 2000 Tom HunterMethods: Scope Rules• The scope for an identifier is the portion of the programin which the identifier can be referenced.• The scopes for an identifier are:• class• block• method
    • 15. Java I--Copyright © 2000 Tom HunterMethod Overloading• Method overloading allows a method name to be re-used.• To overload a method--or to create another version of amethod that already exists--the argument lists for themethods must differ in:• number of arguments• type of arguments• order of arguments• The return type of the method is NOT considered.
    • 16. Java I--Copyright © 2000 Tom HunterEventDelegationModel
    • 17. Java I--Copyright © 2000 Tom HunterEvent Delegation Model• Unlike many other languages--such asVisual Basic--when the Javaprogrammer wishes to programresponses to an event--such as the enterkey being pressed, the event must beentirely programmed.
    • 18. Java I--Copyright © 2000 Tom HunterEvent 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 waspunched.> Vinnie reacts to the problem.
    • 19. Java I--Copyright © 2000 Tom HunterEvent 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 waspressed.> The Listener reacts to the event.
    • 20. Java I--Copyright © 2000 Tom HunterEvent 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.
    • 21. Java I--Copyright © 2000 Tom HunterEvent Delegation ModelEvent SourcestransmitActionEventobjectsto Event Listener(s).
    • 22. Java I--Copyright © 2000 Tom HunterEvent 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 toall registered listeners when that event occurs.• The listener object(s) will then use the details in the eventobject to decide how to react to the event.* A “Listener Object” [an instance of a class] implementsa special interface called a “listener interface.”
    • 23. Java I--Copyright © 2000 Tom HunterEvent Delegation Model• When you ask the listener object to pay attention to yourevent source, that is called registering the listener object withthe source object.• You do that with the following lines of code:eventSourceObject.addEventListener( eventListenerObject );
    • 24. Java I--Copyright © 2000 Tom HunterEvent Delegation Model• Now, the panel object is notified whenever an“action event” occurs in the button.• When you click on a button, the panel objecthears about it.MyPanel panel = new MyPanel();JButton button = new JButton( “Clear” );button.addActionListener( panel );
    • 25. Java I--Copyright © 2000 Tom HunterEvent Delegation Model• Code like this requires that the class the panel comesfrom to implement the appropriate interface.• In this case, class MyPanel must implement theActionListener interface.MyPanel panel = new MyPanel();JButton button = new JButton( “Clear” );button.addActionListener( panel );
    • 26. Java I--Copyright © 2000 Tom HunterEvent Delegation Model• To implement the ActionListener interface, the listenerclass must have a method calledactionPerformed(actionPerformed( ActionEventActionEvent ee ))that receives an ActionEvent object as a parameter.MyPanel panel = new MyPanel();JButton button = new JButton( “Clear” );button.addActionListener( panel );
    • 27. Java I--Copyright © 2000 Tom HunterEvent Delegation Model• Whenever the user clicks the button, the JButtonobject creates an ActionEvent object and callspanel.actionPerformed, passing that eventobject.public class MyPanel extends JPanelimplement ActionListener{public void actionPerformed( ActionEvent e ){// appropriate code to react to event// goes here.}}
    • 28. Java I--Copyright © 2000 Tom HunterEvent Delegation Model: Which Button Was Clicked?• A closer look at the object that is passed, theActionEvent object:• The method getSource() will tell us which objectcreated and sent the ActionEvent object.
    • 29. Java I--Copyright © 2000 Tom HunterEvent 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 ) registersitself with the buttons so that it can listen to them.public void actionPerformed( ActionEvent e ){if ( e.getSource() == button )...}
    • 30. Java I--Copyright © 2000 Tom HunterEvery event handler requires 3 bits of code:1. Code that says the class implements a listener interface:public class MyClass implements ActionListener2.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...}
    • 31. Java I--Copyright © 2000 Tom HunterEvent 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 methodactionPerformed receives an ActionEvent objectthat tells it the details of the event.
    • 32. Java I--Copyright © 2000 Tom Hunterimport 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;
    • 33. Java I--Copyright © 2000 Tom Hunterimport 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, wemust import theevent class API:java.awt.event.*;
    • 34. Java I--Copyright © 2000 Tom Hunterimport 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;
    • 35. Java I--Copyright © 2000 Tom Hunterimport 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 aninterface. You see, although we are directlyinheriting from the class JApplet, we aregetting some functions through the interfacefrom the class ActionListener. We willlearn more about interfaces later.
    • 36. Java I--Copyright © 2000 Tom Hunterimport 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;
    • 37. Java I--Copyright © 2000 Tom Hunterimport 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, acomponent is something we placeon the content pane.
    • 38. 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()
    • 39. 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 camefrom the Content Pane. Here, weare setting the Layout, or how theobjects get stacked on the page.There are many different choicesfor layouts. We will discuss themlater.
    • 40. 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()
    • 41. 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’redefining them. Then, we see how the Container c isusing its method “add” to add the JLabels objectdie1Label to its content pane.
    • 42. 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()
    • 43. 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 buttonroll. We want our same JApplet--the one we are inside ofnow--to listen to for the events. To say that, we use the“this” reference below. It means “this” JApplet will listenfor events that happen to the JButton “roll”. This is called“registering an Action Listener”.
    • 44. 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 followingmethod is performed. It receives anActionEvent object.• In our example, this method just calls anothermethod, play()
    • 45. 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 blockelse{sumOfDice = rollDice();if( sumOfDice == myPoint )gameStatus = WON;elseThis methoddecides whatto do whenthe eventhappens.
    • 46. Java I--Copyright © 2000 Tom HunterInterfaces• When we said our program:implements ActionListenerit was implementing a thing called an interface.If you want to implement the interface ActionListener, itmeans that you must define a method called:public void actionPerformed( ActionEvent e )in your class. (More about Interfaces later…)
    • 47. Java I--Copyright © 2000 Tom HunterLayout Managers• Recall that you use the getContentPane() methodas a starting point when you want to place components ona GUI.• After that, how are your GUI components organized onthe window?• The Layout Manager controls how this happens.A Layout Manager determines theposition and size of every GUI componentattached to a Container.
    • 48. Java I--Copyright © 2000 Tom HunterLayout Managers• Flow Layout is the most basic. It places the objects oneafter another, top to bottom, left to right, on the Container.
    • 49. Java I--Copyright © 2000 Tom HunterLayout Managers• This is the same Applet as on the previous slide. It hasonly be resized to a different shape.
    • 50. Java I--Copyright © 2000 Tom HunterRecursion• For any programming problem, there are usually twoalternative ways to solve it:--iteration and--recursion• Iteration means repeating the same thing a certainnumber 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.
    • 51. Java I--Copyright © 2000 Tom HunterRecursion• If we choose to call a method recursively, it means weare calling it numerous times until we arrive at thesolution.• Ironically, a recursive method can only actually solve thesimplest “base” case.• The other, more complex cases wait until the simplestbase case is solved and then it works from the inside outuntil all the cases are solved.
    • 52. Java I--Copyright © 2000 Tom HunterRecursion 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 addingtogether the previous two numbers.
    • 53. Java I--Copyright © 2000 Tom Hunterimport 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()
    • 54. Java I--Copyright © 2000 Tom Hunterpublic void actionPerformed( ActionEvent e ){long number,fibonacciValue;number = Long.parseLong( num.getText() );showStatus( "Calculating..." ); // status area of AppletfibonacciValue = 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
    • 55. Java I--Copyright © 2000 Tom Hunterpublic 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 thebase case, then the previous copies of the method--thathad been waiting for the else to finish--complete theirexecution from the inside out.
    • 56. Java I--Copyright © 2000 Tom HunterJApplet’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 theirsignatures--they will execute automatically.• If you do not exactly copy their signatures, then youroverride will not automatically be executed.
    • 57. Java I--Copyright © 2000 Tom HunterJApplet’s Methods• In addition to these are several others:init()start()paint()stop()destroy()• As they are inherited, these members are guaranteed tobe called--but still none of them contain any code.• They are all empty, and only contain code when youoverride them and add some.
    • 58. Java I--Copyright © 2000 Tom HunterJApplet’s Methodsinit()• This method is called when the Applet is first created, toperform first-time initialization of the applet.
    • 59. Java I--Copyright © 2000 Tom HunterJApplet’s Methodsstart()• This method is called every time the applet moves intosite on the web browser to permit the applet to start up itsnormal operations ( especially those that are shut off bystop() )• This is called automatically after init().
    • 60. Java I--Copyright © 2000 Tom HunterJApplet’s Methodspaint()• This method does not even come from JApplet orApplet. It is inherited down the hierarchy from the baseclass Component, up three levels of the inheritance tree.• This method is called automatically after init() andstart() have been called.• If you ever resize an applet, first method update() iscalled and update calls paint()
    • 61. Java I--Copyright © 2000 Tom HunterJApplet’s Methodspaint()• If your applet ever gets covered up, then when it returnsto the top it needs to restore itself. Method start() isautomatically called and then method update() (whichcomes from class Component) and finally paint().• So, to recap, anytime you resize your applet, you arefiring method update(), which in turn fires methodpaint().
    • 62. Java I--Copyright © 2000 Tom HunterJApplet’s Methodspaint()• When update() calls paint(), update() sendspaint() a handle to a Graphics object that represents thesurface on which you can paint.
    • 63. Java I--Copyright © 2000 Tom HunterJApplet’s Methodsstop()• This method is called whenever the applet is hidden fromview by going behind another window or beingminimized. This allows the web browser to quit wastingCPU cycles on anything the applet is doing.• Right before the method destroy() is called, thisstop() is first called to halt the applet’s processing.
    • 64. Java I--Copyright © 2000 Tom HunterJApplet’s Methodsdestroy()• This method is called when the applet is being unloadedfrom the web page.• This method permits the final release of memoryresources when the applet is no longer being used.

    ×