Upload
cecil-caldwell
View
214
Download
1
Embed Size (px)
Citation preview
CSE 1301
Lecture 6
Writing Classes
Figures from Lewis, “C# Software Solutions”, Addison Wesley
Richard Gesick
CSE 1301
Topics
• Methods• Return• Parameters• Constructors• Overloading Constructors• Scope
CSE 1301
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
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
CSE 1301
myMethod();
myMethodcompute
Method Control Flow• If the called method is in the same class, only the
method name is needed
CSE 1301
doIt
helpMe
helpMe();
obj.doIt();
main
Method Control Flow• The called method is often part of another
class or object
CSE 1301
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
Return Example
int Sum(int a, int b){ return a + b;
Console.Writeline("This will never be displayed");
}
CSE 1301
Method Header• A method declaration begins with a method
headerchar calc (int num1, int num2, string message)
methodname
returntype
parameter list
The parameter list specifies the typeand name of each parameter
The name of a parameter in the methoddeclaration is called a formal parameter
CSE 1301
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 expressionmust be consistent withthe return type
sum and resultare local data
They are created each time the method is called, and are destroyed when it finishes executing
CSE 1301
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)
CSE 1301
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
Parameters & Scope• Because variables are only visible within the
scope in which they are declared, no one else can “see” them
• This is a good thing for protection/encapsulation• But we need a way of moving data within our
program– Making everything “global” is a bad idea– There are times when we need to pass on some
data to the method for it to work on that data
CSE 1301
Parameters
• A method is defined by its– Name– Return type– PARAMETERS (the stuff in the parenthesis)
• When we call a method, we need to pass the correct number and type of parameters– “Speak the language” of the method
CSE 1301
Parameters• When a method is called, the actual parameters in the
invocation are copied into the formal parameters in the method header
char calc (int num1, int num2, string message)
{ int sum = num1 + num2; char result = message.charAt(sum);
return result;}
ch = obj.calc (25, count, "Hello");
CSE 1301
Constructors
• Special methods that are called when an object is instantiated using the new keyword.
• A class can have several constructors. • The job of the class constructors is to initialize
the instance variables of the new object.
CSE 1301
Constructors• So far, we’ve seen attributes and methods• Constructor is a unique method
– Named same as the class name– Automatically called when class is instantiated– Useful for setting attributes & initializing the instance– No return type (not even void)– Must be public
• Default constructor is used unless you specify a constructor
• For each attribute in the class, assign something to it in the constructor (initialize)
CSE 1301
class BMW_Z4 { private int modelYear; private string licensePlate; private bool topUp;
public BMW_Z4 () { ModelYear = 2004; TopUp = false; LicensePlate = "DEALER"; }
...}
Constructor Example
CSE 1301
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
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
Overloading Exampleint Square (int i){ return i * i;}
float Square (float i){ return i * i;}static void Main(){ ... float x = Square(5.3f); int y = Square(9); ...}
CSE 1301
Constructor Overloading
class BMW_Z4{ ... 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 commoninitialization in aseparate function
Notice same methodname, different parameters
CSE 1301
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-23Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
CSE 1301
Defining a ConstructorSyntax: 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
Constructor Examplespublic 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
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
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
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
CSE 1301
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.
CSE 1301
Accessor Methods
• Example: the accessor method for model from the Auto class
public string getModel( ) {
return model; }
CSE 1301
Mutator Methods• Allow client to change the values of instance
variables
public void setInstanceVariable( dataType newValue ){ // validate newValue, // then assign to instance variable}
This is the same as the “set” property.
CSE 1301
Software Engineering Tip
• Write the validation code for the instance variable in the mutator method and have the constructor call the mutator method to validate and set initial values
• This eliminates duplicate code and makes the program easier to maintain
CSE 1301
Common Error Trap • Do not declare method parameters.
– Parameters are defined already and are assigned the values sent by the client to the method.
• Do not give the parameter the same name as the instance variable.– The parameter has name precedence so it "hides" the
instance variable.• Do not declare a local variable with the same name
as the instance variable.– Local variables have name precedence and hide the
instance variable.
CSE 1301
The Object Reference this• How does a method know which object's data to use? • this is an implicit parameter sent to methods and is
an object reference to the object for which the method was called.
• When a method refers to an instance variable name, this is implied
• Thus: variableName model is understood to be is understood to be this.variableName this.model
CSE 1301
Using this in a Mutator Methodpublic void setInstanceVariable( dataType instanceVariableName ){ this.instanceVariableName = instanceVariableName;}
• Example:public void setModel( string model ){ this.model = model;}
this.model refers to the instance variable.model refers to the parameter.
CSE 1301
Another Example
• Suppose we wanted a new object to represent a day of the year.
• What data should we store?• What operations are available?• What should be public?• What should be private?
CSE 1301
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;
CSE 1301
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.
CSE 1301
Rules for static and Non-static Methodsstatic
MethodNon-static
Method
Access instance variables? no yes
Access static class variables?
yes yes
Call static class methods? yes yes
Call non-static instance methods?
no yes
Use the object reference this?
no yes