Methods and Parameters Chapter 5 How to split large programs into isolated sections. Focus on one part of the problem – which can be “called” on or “invoked” by name
paper.drawRect (10, 20, 60, 60); drawRect is called and passed a starting x,y value and an ending x,y value
Writing your own methods Page “LogoMethod” program private void drawLogo (Graphics drawingArea, int xPos, int yPos) { –Method header for drawLogo method –Formal parameter list inside parenthesis Private method may be called by another method in the same class Void = drawLoge returns nothing, other methods may return any type. Body of method will be enclosed by { }
Calling a method drawLogo ( paper, 10, 20); Call must include name of method and arguments (in correct order, number, type) –If any are required
Formal vs. Actual parameters Formal parameters in list –drawLogo (Graphics drawingArea, int xPos, int yPos) –drawingArea, xPos and yPos are formal Actual parameters are given in call… –drawLogo ( paper, 10, 20); –Paper, 10 and 20 are Actual
Trianglemethod Page Page 70 drawTriangle2 (80, 100) (80, )( , ) W = 60 H = 70
Scope local vs. class Pages Name Clashes x, y, z may exist locally in any method, even if they are declared as different types Java treats them a different
Event handling Called by Java run time system main called automatically actionPerformed called when buttons clicked (or another even occurs) A return sends a result back to the rest of the program. Page 73 program “AreaMethod” returns a value “area” to the calling method answer = areaRectangle ( 30, 40);
“drawHouse” page Using drawtriangle and drawRectangle to draw a house
actionPerformed calls drawHouse drawHouse calls drawRect drawHouse calls drawTriangle drawTriangle calls drawLine areaHouse calls areaRectanglr and areaTriangle adds the results, returns the sum.
overloading areaTriangle has an int and a double version based upon the call (int or double) Java decides which to use by type passed in the call