Download Method Declarations - Methods - Lecture Slides | CSE 1301 and more Study notes Computer Science in PDF only on Docsity!
CSE 1301
Lecture 4B
Writing Classes
Figures from Lewis, “C# Software Solutions”, Addison Wesley
Briana B. Morrison
CSE 1301 (^) 4B-
Topics
- Methods
- Return
- Parameters
- Constructors
- Overloading Constructors
- Scope
CSE 1301 (^) 4B-
Method Declarations
- Let’s now examine method declarations in more detail
- A method declaration specifies the code that will be executed when the method is invoked (called)
- When a method is invoked, the flow of control jumps to the method and executes its code
- When complete, the flow returns to the place where the method was called and continues
- The invocation may or may not return a value, depending on how the method is defined CSE 1301 (^) 4B-
Methods
- Used to group a set of instructions
- Given a name (so we can refer to it later)
- This name represents the instructions
- Methods can be public or private
- Public if someone outside the class should access/invoke them
- Private if used internal to the class
myMethod();
compute myMethod
Method Control Flow
- If the called method is in the same class,
only the method name is needed
doIt helpMe
obj.doIt(); helpMe();
main
Method Control Flow
- The called method is often part of another
class or object
CSE 1301 (^) 4B-
A Method Returns
- When the method is done, control returns
to where we “left off” in the caller
- As in math, functions/methods can
evaluate to something
- We should be able to “return” a value
- The return statement halts execution
within the method and (optionally) returns
a value
CSE 1301 (^) 4B-
Return Example
int Sum(int a, int b) { return a + b;
Console.Writeline("This will never be displayed"); }
CSE 1301 (^) 4B-
Method Header
- A method declaration begins with a
method header
char calc (int num1, int num2, string message)
method name return type
parameter list
The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter CSE 1301 (^) 4B-
Method Body
- The method header is followed by the method body char calc (int num1, int num2, string message) { int sum = num1 + num2; char result = message.charAt(sum); return result; }
The return expression must be consistent with the return type
sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing
Method Body
- The code that performs the method's
function is written between the
beginning and ending curly braces.
- In the method body, a method can
declare variables, call other methods,
and use other program structures
( if/else statements, while loops, for
loops, switch statements, and do/while
loops)
The return Statement
- The return type of a method indicates the type of value that the method sends back to the calling location
- A method that does not return a value has a void return type
- A return statement specifies the value that will be returned return expression ;
- Its expression must conform to the return type
CSE 1301 (^) 4B-
Multiple Constructors (overloading)
- Constructors are used to initialize our
objects
- We can use parameters to the
constructor to customize the initialization
- Sometimes we have more or less data
to use in the customization
- We’d like to be able to pass in only what
we know
1-19 (^) CSE 1301 (^) 4B-
Overloading
- Overloading involves using the same
method/function name
- Vary the number of parameters
- Vary the type of parameters
- Cannot just change return type (ambiguity in invocation)
- Useful to keep things simple
- Squaring a number…
CSE 1301 (^) 4B-
Overloading Example
int Square (int i) { return i * i; } float Square (float i) { return i * i; } static void Main() { ... float x = Square(5.3); int y = Square(9); ... } CSE 1301 (^) 4B-
Constructor Overloading
class BMW_Z { ... public BMW_Z4 () { Initialize(0, 2004, false); } public BMW_Z4 (int my) { Initialize(0, my, false); } private Initialize(int cs, int my, bool tu) { currentSpeed = cs; ModelYear = my; TopUp = tu; } ... }
Place common initialization in a separate function
Notice same method name, different parameters
CSE 1301 (^) 4B-
Which is Called?
BMW_Z4 myCar = new BMW_Z4(); BMW_Z4 yourCar = new BMW_Z4(2007); BMW_Z4 herCar = new BMW_Z4(2008);
- The constructor with the matching
parameter definition will be called
- If no parameters, the () constructor
- If one parameter, the (int) constructor
2- Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison- Wesley (^) CSE 1301 (^) 4B-
Defining a Constructor
Syntax: public ClassName( parameter list ) { // constructor body } Note: no return value, not even void!
- Each constructor must have a different number of parameters or parameters of different types
- Default constructor : a constructor that takes no arguments.
CSE 1301 (^) 4B-
Constructor Examples
public class Card { private int value; private string suit; //default constructor public Card ( ) { value = 1; suit = “Spades”; } // specific constructor public Card (int initValue, string initSuit) { value = initValue; suit = initSuit; } } CSE 1301 (^) 4B-
Class Scope
- Instance variables have class scope
- Any constructor or method of a class can directly refer to instance variables.
- Methods also have class scope
- Any method or constructor of a class can call any other method of a class (without using an object reference).
CSE 1301 (^) 4B-
Local Scope
- A method's parameters have local scope , meaning that: - a method can directly access its parameters. - a method's parameters cannot be accessed by other methods.
- A method can define local variables which also have local scope, meaning that: - a method can access its local variables. - a method's local variables cannot be accessed by other methods.
CSE 1301 (^) 4B-
Summary of Scope
- A method in a class can access:
- the instance variables of its class
- any parameters sent to the method
- any variable the method declares from the point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first
- any methods in the class
Accessor Methods
- Clients cannot directly access private
instance variables, so classes provide
public accessor methods with this standard
form:
public returnType getInstanceVariable( ) { return instanceVariable; }
(returnType is the same data type as the
instance variable)
This is the same as the “get” property.
Accessor Methods
- Example: the accessor method for
model from the Auto class
public string getModel( ) { return model; }
CSE 1301 (^) 4B-
Work Example Here
CSE 1301 (^) 4B-
static Variables
- Also called class variables
- One copy of a static variable is created per class
- static variables are not associated with an object
- static constants are often declared as public
- To define a static variable, include the keyword static in its definition:
- Syntax: accessSpecifier static dataType variableName;
- Example: public static int countAutos = 0;
static Methods
- Also called class methods
- Often defined to access and change static
variables
- static methods cannot access instance
variables:
- static methods are associated with the class, not with any object.
- static methods can be called before any object is instantiated, so it is possible that there will be no instance variables to access.
Rules for static and Non- static
Methods
Use the object reference no yes this?
Call non- static instance no yes methods?
Call static class methods? yes yes
Access static class yes yes variables?
Access instance no yes variables?
Non- static Method
static Method