40
METHODS AND SCOPE CSCE 1030

METHODS AND SCOPE CSCE 1030. More on Methods This is chapter 6 in Small Java

Embed Size (px)

Citation preview

Page 1: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

METHODS AND SCOPE

CSCE 1030

Page 2: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

More on Methods

This is chapter 6 in Small Java

Page 3: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Creating a Method

The author of a class:public class Player {

private int health; private int shields; private int ammo;

public void firedUpon( int damage ) {

health = health – damage; if (health <= 0 ) playDeathAnimation ( );

}}

public class Player {

private int health; private int shields; private int ammo;

public void firedUpon( int damage ) {

health = health – damage; if (health <= 0 ) playDeathAnimation ( );

}}

As the author of this class, I write

this method

I call another method of the class

from here

Page 4: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Using a Method

The user or ‘client’ of the Player class:

public class Game {

Player p1 = new Player ( ); // calls the constructor

p1.firedUpon (45);

}

public class Game {

Player p1 = new Player ( ); // calls the constructor

p1.firedUpon (45);

}

I create an Object named p1

We say p1 is of type Player, or p1 is a Player

I call firedUpon

Page 5: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Gets and Sets

Class data is usually private Remember: private means ‘only available

within the class’ We can access that data with ‘Get’ and

‘Set’ methods If we just allowed anyone access to the

‘speed’ variable of the car, someone might set it to 9999999.

With a ‘Set’ method, we can check for ludicrous speed

Page 6: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Set Method

public class Player {

private int health; private int shields; private int ammo;

public void setShield ( int shieldValue ) {

shields = shieldValue; } public void firedUpon( int damage ) {

health = health – damage; if (health <= 0 ) playDeathAnimation ( );

}}

public class Player {

private int health; private int shields; private int ammo;

public void setShield ( int shieldValue ) {

shields = shieldValue; } public void firedUpon( int damage ) {

health = health – damage; if (health <= 0 ) playDeathAnimation ( );

}}

Send setShield the new

value

Page 7: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Get Method

public class Player {

private int health; private int shields; private int ammo;

public int getShield ( ) {

return shields; }

public void firedUpon( int damage ) {

health = health – damage; if (health <= 0 ) playDeathAnimation ( );

}}

public class Player {

private int health; private int shields; private int ammo;

public int getShield ( ) {

return shields; }

public void firedUpon( int damage ) {

health = health – damage; if (health <= 0 ) playDeathAnimation ( );

}}

Return the shields value to the caller or the client (the

program that called this method)

Page 8: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Methods – a few notes

Methods go inside a class – they are the actions that a car can perform. MyCar.turnRight( ); // calling the turnRight

method

No methods inside other methods When defining a method in your class, you

need to specify a return type (even if it is void) Except the constructor method – no return type

Page 9: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Methods – a few notes

If you are creating a class, give your methods a small, clearly defined purpose Good: fireWeapon( ) Bad: go ( )

Methods are sometimes referred to as functions or procedures.

Classes are composed of methods and data. The methods are the verbs – what your class can ‘do’.

Page 10: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Methods – a few notes

You can pass more than one thing to a method

public void driveCar (int from, int to) { … }

Make sure you send them in the right order when you call this function!

A class method can call another class method. withdrawCash( ) can call notifyCustomer( ) if

balance = 0

Page 11: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

11

1 // Fig. 6.3: MaximumFinder.java

2 // Programmer-declared method maximum.

3 import java.util.Scanner;

4

5 public class MaximumFinder

6 {

7 // obtain three floating-point values and locate the maximum value

8 public void determineMaximum()

9 {

10 // create Scanner for input from command window

11 Scanner input = new Scanner( System.in );

12

13 // obtain user input

14 System.out.print(

15 "Enter three floating-point values separated by spaces: " );

16 double number1 = input.nextDouble(); // read first double

17 double number2 = input.nextDouble(); // read second double

18 double number3 = input.nextDouble(); // read third double

19

20 // determine the maximum value

21 double result = maximum( number1, number2, number3 );

22

23 // display maximum value

24 System.out.println( "Maximum is: " + result );

25 } // end method determineMaximum

26

Prompt the user to enter and read three double values

Call method maximum

Display maximum value

Page 12: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

1227 // returns the maximum of its three double parameters

28 public double maximum( double x, double y, double z )

29 {

30 double maximumValue = x; // assume x is the largest to start

31

32 // determine whether y is greater than maximumValue

33 if ( y > maximumValue )

34 maximumValue = y;

35

36 // determine whether z is greater than maximumValue

37 if ( z > maximumValue )

38 maximumValue = z;

39

40 return maximumValue;

41 } // end method maximum

42 } // end class MaximumFinder

Declare the maximum method

Compare y and maximumValue

Compare z and maximumValue

Return the maximum value

Page 13: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

13 1 // Fig. 6.4: MaximumFinderTest.java

2 // Application to test class MaximumFinder.

3

4 public class MaximumFinderTest

5 {

6 // application starting point

7 public static void main( String args[] )

8 {

9 MaximumFinder maximumFinder = new MaximumFinder();

10 maximumFinder.determineMaximum();

11 } // end main

12 } // end class MaximumFinderTest Enter three floating-point values separated by spaces: 9.35 2.74 5.1 Maximum is: 9.35 Enter three floating-point values separated by spaces: 5.8 12.45 8.32 Maximum is: 12.45 Enter three floating-point values separated by spaces: 6.46 4.12 10.54 Maximum is: 10.54

Create a MaximumFinder object

Call the determineMaximum method

Page 14: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Up to this point…

Create an object of a class Car myCar = new Car( ); This Car constructor takes no parameters

Call a method on that object myCar.turnLeft( );

A driving simulator is filled with Car objects Another class DrivingSimulator has the main

method, where we create the cars and drive around

Page 15: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Objects

This is object oriented programming Car objects were created to simulate

driving And everything seemed good…

Page 16: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

But…

The object oriented model doesn’t always fit with the real world…

Consider the square root function – it is used frequently, so it must be built into Java, right?

So, do we follow the traditional model with a Math class? Math myMath = new Math( ); myMath.squareRoot( 9 );

Page 17: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

But…

This object-oriented stuff doesn’t really fit with the real world in this case

There really is only one ‘Math’, not myMath and yourMath.

So…

Page 18: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Static Methods

All methods in Math are ‘static’

Static Methods belong to the class, not the object

Math is in Java.lang, so no need to import it. Java.lang is used so frequently, you get it for free

Page 19: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Static Methods

Non-static (Instance methods)… myCar.turnLeft( );

Static Method Math.sqrt ( 9 );

With Static methods, we don’t need an object!

Object name

Method name

CLASS name

Method name

Page 20: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Static

Methods and data can be declared static

public class superHero { private static String heroMotto = “I am a crime fighter.”;

public static String getMotto ( ) {

return heroMotto;

}

}

public class superHero { private static String heroMotto = “I am a crime fighter.”;

public static String getMotto ( ) {

return heroMotto;

}

}

A static method using static data

Page 21: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Static

Static methods CANNOT use non-static data or methods in the class.

Why not?

Page 22: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Static Methods

An online tutorial for static methods

The Main method is declared static so that we don’t have to create an object of the class to use main.

Page 23: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Calling a Method

Three ways to call a method

methodName( 3 ); Nothing before the name, so this must be a

method in the same class (that accepts an integer)

objectName.methodName( 3 ); methodName is a non-static method

className.methodName(3); Only if methodName is a static method

Page 24: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Calling a method

The program transfers control to the code in the method

It will return to the caller when it encounters… A ‘return’ statement Or, the end of the method }

Page 25: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Final keyword

‘final’ means it does not change – for constants in the program

Like PI

Somewhere in the Math class… final static double PI = 3.14159…

Page 26: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Methods in Math Class

Method Description Example

abs( x ) absolute value of x abs( 23.7 ) is 23.7 abs( 0.0 ) is 0.0 abs( -23.7 ) is 23.7

ceil( x ) rounds x to the smallest integer not less than x

ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x (x in radians) cos( 0.0 ) is 1.0

exp( x ) exponential method ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906

floor( x ) rounds x to the largest integer not greater than x

Floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0

log( x ) natural logarithm of x (base e) log( Math.E ) is 1.0 log( Math.E * Math.E ) is 2.0

max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3

min( x, y ) smaller value of x and y min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7

pow( x, y ) x raised to the power y (i.e., xy) pow( 2.0, 7.0 ) is 128.0 pow( 9.0, 0.5 ) is 3.0

sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0.0

sqrt( x ) square root of x sqrt( 900.0 ) is 30.0

tan( x ) trigonometric tangent of x (x in radians) tan( 0.0 ) is 0.0

Page 27: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

The Java API

Don’t reinvent the wheel Use the classes that someone else wrote

Example Libraries follow.

Page 28: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Package Description

java.applet The Java Applet Package contains a class and several interfaces required to create Java

applets—programs that execute in Web browsers. (Applets are discussed in Chapter 20,

Introduction to Java Applets; interfaces are discussed in Chapter 10, Object_-Oriented

Programming: Polymorphism.)

java.awt The Java Abstract Window Toolkit Package contains the classes and interfaces required

to create and manipulate GUIs in Java 1.0 and 1.1. In current versions of Java, the Swing

GUI components of the javax.swing packages are often used instead. (Some elements

of the java.awt package are discussed in Chapter 11, GUI Components: Part 1,

Chapter 12, Graphics and Java2D, and Chapter 22, GUI Components: Part 2.)

java.awt.event The Java Abstract Window Toolkit Event Package contains classes and interfaces that

enable event handling for GUI components in both the java.awt and javax.swing

packages. (You will learn more about this package in Chapter 11, GUI Components: Part

1 and Chapter 22, GUI Components: Part 2.)

java.io The Java Input/Output Package contains classes and interfaces that enable programs to

input and output data. (You will learn more about this package in Chapter 14, Files and

Streams.)

java.lang The Java Language Package contains classes and interfaces (discussed throughout this

text) that are required by many Java programs. This package is imported by the compiler

into all programs, so the programmer does not need to do so.

Page 29: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Package Description java.net The Java Networking Package contains classes and interfaces that enable programs to

communicate via computer networks like the Internet. (You will learn more about this in

Chapter 24, Networking.)

java.text The Java Text Package contains classes and interfaces that enable programs to manipulate

numbers, dates, characters and strings. The package provides internationalization capabilities

that enable a program to be customized to a specific locale (e.g., a program may display strings

in different languages, based on the user’s country).

java.util The Java Utilities Package contains utility classes and interfaces that enable such actions as date

and time manipulations, random-number processing (class Random), the storing and processing

of large amounts of data and the breaking of strings into smaller pieces called tokens (class

StringTokenizer). (You will learn more about the features of this package in Chapter 19,

Collections.)

javax.swing The Java Swing GUI Components Package contains classes and interfaces for Java’s Swing

GUI components that provide support for portable GUIs. (You will learn more about this

package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI Components: Part 2.)

javax.swing.event The Java Swing Event Package contains classes and interfaces that enable event handling (e.g.,

responding to button clicks) for GUI components in package javax.swing. (You will learn

more about this package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI

Components: Part 2.)

Page 30: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Scope

Scope refers to where a variable is ‘visible’, or where you can use a variable

It depends on where you declare the variable int x = 0; wherever a line like this

appears

Page 31: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Scope

{ } form a ‘block’ of code. Think of this like a room with tinted glass. You can see out, but not in.

While ( x < 10 ) {

int x = 0; // created inside the while loop // and not visible outside it.

}

While ( x < 10 ) {

int x = 0; // created inside the while loop // and not visible outside it.

}

Page 32: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

public class ScopeExample {

int classVariable = 0; // class level variable

methodVariable = 3; ??

}

public class ScopeExample {

int classVariable = 0; // class level variable

methodVariable = 3; ??

}

Scope

public void ScopeMethod ( ) { int methodVariable = 0; // created inside the method

classVariable = 2; // I can see out, through my own window tint loopVariable = 3; // I can’t see inside the while loop – the window is tinted}

public void ScopeMethod ( ) { int methodVariable = 0; // created inside the method

classVariable = 2; // I can see out, through my own window tint loopVariable = 3; // I can’t see inside the while loop – the window is tinted}

while ( x < 10 ) {

int loopVariable = 0; // created inside the while loop

// and not visible outside it.methodVariable = 3; // can see out of my tinted

roomclassVariable = 4;

}

while ( x < 10 ) {

int loopVariable = 0; // created inside the while loop

// and not visible outside it.methodVariable = 3; // can see out of my tinted

roomclassVariable = 4;

}

Page 33: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

Method Overloading

Having 2 or more methods with the same name

But… they accept different parameters…

We may want to be able to square ints and floats

Best to look at an example

Page 34: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

34

Correctly calls the “square of int” method

Correctly calls the “square of double” method

Declaring the “square of int” method

Declaring the “square of double” method

Page 35: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

35

Page 36: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

36

Same method signature

Compilation error

Page 37: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

37

(Optional) GUI and Graphics Case Study: Colors and Filled Shapes

Color class of package java.awt Represented as RGB (red, green and blue)

values Each component has a value from 0 to 255

13 predefined static Color objects: Color.Black, Coor.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE and Color.YELLOW

Page 38: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

38

(Optional) GUI and Graphics Case Study: Colors and Filled Shapes (Cont.)

fillRect and fillOval methods of Graphics class Similar to drawRect and drawOval but draw

rectangles and ovals filled with color First two parameters specify upper-left corner

coordinates and second two parameters specify width and height

setColor method of Graphics class Set the current drawing color (for filling

rectangles and ovals drawn by fillRect and fillOval)

Page 39: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

39

Import Color class

Page 40: METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java

40

Available in the web compiler HERE