Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "METHODS AND SCOPE CSCE 1030. More on Methods  This is chapter 6 in Small Java."— Presentation transcript:

1 METHODS AND SCOPE CSCE 1030

2 More on Methods  This is chapter 6 in Small Java

3 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

4 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

5 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

6 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

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

8 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

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

10 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

11 11 Prompt the user to enter and read three double values Call method maximum Display maximum value

12 12 Declare the maximum method Compare y and maximumValue Compare z and maximumValue Return the maximum value

13 13 Create a MaximumFinder object Call the determineMaximum method

14 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

15 Objects  This is object oriented programming  Car objects were created to simulate driving  And everything seemed good…

16 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 );

17 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…

18 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

19 Static Methods  Non-static (Instance methods)…  myCar.turnLeft( );  Static Method  Math.sqrt ( 9 );  With Static methods, we don’t need an object! Object nameMethod name CLASS nameMethod name

20 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

21 Static  Static methods CANNOT use non-static data or methods in the class.  Why not?

22 Static Methods  An online tutorial for 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.

23 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

24 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 }

25 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…

26 Methods in Math Class

27 The Java API  Don’t reinvent the wheel  Use the classes that someone else wrote  Example Libraries follow.

28

29

30 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

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

32 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 room classVariable = 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 room classVariable = 4; }

33 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

34 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

35 35

36 36 Same method signature Compilation error

37 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

38 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 )

39 39 Import Color class

40 40 Available in the web compiler HEREHERE


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

Similar presentations


Ads by Google