Upload
lenard-owen
View
212
Download
0
Tags:
Embed Size (px)
Citation preview
CSE 1301
Lecture 4
Using Classes
Figures from Lewis, “C# Software Solutions”, Addison Wesley
Richard Gesick
CSE 1301
Topics
• Class Basics and Benefits• Creating Objects• .NET Architecture and Base Class Libraries• Random Class• Math Class
CSE 1301
Object-Oriented Programming
• Classes combine data and the methods (code) to manipulate the data
• Classes are a template used to create specific objects
• All C# programs consist of at least one class.
CSE 1301
Example
• Student class– Data: name, year, and grade point average– Methods: store/get the value of each piece of
data, promote to next year, etc.• Student Object: student1
– Data: Maria Gonzales, Sophomore, 3.5
CSE 1301
Some Terminology
• Object reference: identifier of the object• Instantiating an object: creating an object of a
class• Instance of the class: the object• Methods: the code to manipulate the object
data• Calling a method: invoking a service for an
object.
CSE 1301
Class Data
• Members of a class: the class's fields and methods
• Fields: instance variables and class variables – Fields can be:
• any primitive data type (int, double, etc.)• objects
• Instance variables: variables defined in the class and given values in the object
CSE 1301
What’s in a Class
Class contains
Members are
Fields
Methods
Instance variables
Class variables
CSE 1301
Encapsulation
• Instance variables are usually declared to be private, which means users of the class must reference the data of an object by calling methods of the class.
• Thus the methods provide a protective shell around the data. We call this encapsulation.
• Benefit: the class methods can ensure that the object data is always valid.
CSE 1301
Naming Conventions
• Class names: start with a capital letter• Object references: start with a lowercase
letter• In both cases, internal words start with a
capital letter• Example: class: Student objects: student1, student2
CSE 1301
1. Declare an Object Reference
Syntax: ClassName objectReference; or ClassName objectRef1, objectRef2…;• Object reference holds address of object• Example:
– Date d1;• d1 contains the address of the object, but the
object hasn’t been created yet
CSE 1301
2. Instantiate an Object
• Objects MUST be instantiated before they can be used
• Call a constructor using new keyword• Constructor has same name as class.• Syntax: objectReference = new ClassName( arg list );• Arg list (argument list) is comma-separated list
of initial values to assign to object data, and may be empty
CSE 1301
Date Class APIConstructor: special method that creates an
object and assigns initial values to dataDate Class Constructor Summary
Date( )
creates a Date object with initial month, day, and year values of 1, 1, 2000
Date( int mm, int dd, int yy )
creates a Date object with initial month, day, and year values of mm, dd, and yy
CSE 1301
Instantiation Examples
Date independenceDay;independenceDay = new Date(7,4, 1776 );
Date graduationDate = new Date(5,15,2008);
Date defaultDate = new Date( );
CSE 1301
Objects After Instantiation
Object Instances
CSE 1301
Object Reference vs. Object Data
• Object references point to the location of object data.
• An object can have multiple object references pointing to it.
• Or an object can have no object references pointing to it. If so, the garbage collector will free the object's memory
CSE 1301
Creating Aliases
Date hireDate = new Date( 2, 15, 2003 );Date promotionDate = new Date( 9, 28, 2004 );
promotionDate = hireDate;
int x = 5, y = 3;x = y;
CSE 1301
Two References to an Object • After program runs, two object references point to
the same object
CSE 1301
null Object References
• An object reference can point to no object. In that case, the object reference has the value null
• Object references have the value null when they have been declared, but have not been used to instantiate an object.
• Attempting to use a null object reference causes a run time exception.
CSE 1301
NullReference Date aDate;aDate.setMonth( 5 );Date independenceDay = new Date( 7, 4, 1776 );// set object reference to nullindependenceDay = null;
// attempt to use object referenceindependenceDay.setMonth(5);
CSE 1301
String and StringBuilder• string is like a primitive data type but creates
an immutable object– Once created, cannot be changed– Does not need to be instantiated
• Stringbuilder is a class– Must be instantiated– Can be changed
• Use StringBuilder when many concatenations are needed
CSE 1301
Reusability
• Reuse: class code is already written and tested, so you build a new application faster and it is more reliable
• Example: A Date class could be used in a calendar program, appointment-scheduling program, online shopping program, etc.
CSE 1301
How To Reuse A Class
• You don't need to know how the class is written.
• You do need to know the application programming interface (API) of the class.
• The API is published and tells you:– How to create objects– What methods are available– How to call the methods
CSE 1301
The Argument List in an API
• Pairs of “dataType variableName”• Specify
– Order of arguments– Data type of each argument
• Arguments can be:– Any expression that evaluates to the specified
data type
CSE 1301
Method Classifications
• Accessor methods– Gets the values of object data
• Mutator methods– Writes/changes values of object data
• Others to be defined later
CSE 1301
Dot Notation
• Use when calling method to specify which object's data to use in the method
• Syntax:objectReference.methodName( arg1, arg2, … )
• Note: no data types are specified in the method call; arguments are values only!
CSE 1301
Calling a Method
CSE 1301
• When calling a method, include only expressions in your argument list. Including data types in your argument list will cause a compiler error.
• If the method takes no arguments, remember to include the empty parentheses after the method's name. The parentheses are required even if there are no arguments.
• The following examples use string class properties and methods
CSE 1301
Length Property
28
public int Length { get; } The number of characters in the current string.RemarksThe Length property returns the number of Char objects in this instance, not the number of Unicode characters. Example: string h= “hello”; int len = h.Length; len has a value of 5
CSE 1301
To upper and lower case
29
public string ToLower() Return Value: A string in lowercase.
public string ToUpper() Return Value: A string in uppercase.
Example: string myString = “good luck”;myString = myString.ToUpper();myString now has the value “GOOD LUCK”
CSE 1301
IndexOf methods
30
public int IndexOf( char value ) The zero-based index position of value if that character is found, or -1 if it is not.public int IndexOf( string value)The zero-based index position of value if that string is found, or -1 if it is not.
string myString= “hello world”;int e_index=myString.IndexOf(‘e’); // e_index= 1int or_index= myString.IndexOf(“or”); //or_index=7
CSE 1301
Substring methods
31
public string Substring( int startIndex, int length ) A string that is equivalent to the substring of length length that begins at startIndex in this instance
public string Substring( int startIndex) A string that begins at startIndex and continues to the end of the source string
string h= “hello”;string s= h.Substring(1,3); //s = “ell”string t = h.Substring (2); //t=“llo”
CSE 1301
.NET Architecture
• Framework • When you press F5
– source code compiled into IL– submitted to .NET engine for execution
CSE 1301
CSE 1301
Base Class Libraries and The C# API• This link will take you to the .Net framework
class library.• https://
msdn.microsoft.com/en-us/library/gg145045%28v=VS.110%29.aspx
• On that page most of the classes you will need are in the System namespace.
34
CSE 1301
using Declaration
• Must have using statement to use values in library:using System.Text;
• Or you can fully qualify:System.Text.StringBuilder phrase = new System.Text.StringBuilder (“Change is inevitable”);
CSE 1301
CSE 1301
Random Class
• To generate random numbers• Generates a pseudorandom number
(appearing to be random, but mathematically calculated based on seed value)
3-37
CSE 1301
Random API
3-38
CSE 13013-39
The upper bound in the Random class is exclusive
CSE 13013-40
CSE 1301
Math Class• Basic mathematical functions• All methods are static methods (class
methods)– invoked through the name of the class– no need to instantiate object
• Two static constants– PI = the value of pi – E = the base of the natural logarithm
3-41
CSE 1301
Calling static Methods• Use dot syntax with class name instead of
object reference• Syntax:ClassName.methodName( args )
• Example:int absValue = Math.Abs( -9 );
• abs is a static method of the Math class that returns the absolute value of its argument (here, -9).
3-42
CSE 13013-43
CSE 13013-44
CSE 13013-45
CSE 1301
Summary
• What did you learn?
• Muddiest Point