inf1030-05-creating-your-own-classes
inf1030-05-creating-your-own-classes
Own Classes
1
Objectives
• Become familiar with the components of a
class
• Write instance methods and properties used
for object-oriented development
• Create and use constructors to instantiate
objects
• Call instance methods including mutators and
accessors
• Become familiar with auto property initializers
2
The Object Concept
• Solution is defined in terms of a
collection of cooperating objects
• Class serves as template from which
many objects can be created
• Abstraction
– Attributes (data)
– Behaviors (processes on the data)
3
Private Member Data
• All code you write is placed in a class
• When you define a class, you declare
instance variables or fields that
represent state of an object
– Fields are declared inside the class, but
not inside any specific method
– Fields become visible to all members of
the class, including all of the methods
• Data members are defined to have
private access 4
Private Member Data
(continued)
public class Student
{
private int studentNumber;
private string studentFirstName;
private string studentLastName;
private int score1;
private int score2;
private int score3;
private string major;
5
Add a Class
• Use the PROJECT menu or the
Solution Explorer Window
• Right-mouse click and select the option
Add, Class
• Solution Explorer Window enables
you to create a class diagram
6
Class Diagram
Open the
Class
Diagram
from
Solution
Explorer,
View
Class
Diagram
Figure 1 Student class diagram created in Visual Studio
7
Class Diagram (continued)
• After the class
diagram is
created, add
the names of
data members
or fields and
methods using
the Class
Details section
Right click on
class diagram to
open Class
8
Details window
Class Diagram (continued)
• When you
complete class
details using the
Class Diagram
tool, code is
automatically
placed in the file.
9
Constructor
• Special type of method used to create
objects
– Create instances of class
• Instantiate the class
• Constructors differ from other methods
– Constructors do not return a value
• Also do not include keyword void
– Constructors use same identifier (name)
as class
• Constructors use public access 10
Constructor (continued)
• public access modifier is always
associated with constructors
//Default constructor
public Student ( )
{
}
//Constructor with one parameter
public Student (int sID )
{
studentNumber = sID;
}
11
Constructor (continued)
//Constructor with three parameters
public Student (string sID, string firstName, string
lastName)
{
studentNumber = sID;
studentFirstName = firstName;
studentLastName = lastName;
}
• Design classes to be as flexible and as
full-featured as possible
– Include multiple constructors 12
Writing Your Own Instance
Methods
• Constructors
• Accessors
• Mutators
• Other methods to perform behaviors of
the class
13
Writing Your Own Instance
Methods
• Do not use static keyword
– Static associated with class method
• Constructor – special type of instance
method
– Do not return a value
– void is not included
– Same identifier as the class name
– Overloaded
– Default constructor
• No arguments
• Write one constructor and you lose the default
one 14
Accessor
• Getters
• Returns the current value
• Standard naming convention → prefix
with “Get”
– Accessor for noOfSquareYards
public double GetNoOfSqYards( )
{
return noOfSqYards;
}
• Properties serve purpose Accessor
15
Mutators
• Setters
• Normally includes one parameter
• Method body → single assignment
statement
• Standard naming convention → prefix
with ”Set”
• Can be overloaded
16
Mutator Examples
public void SetNoOfSqYards(double squareYards)
{
noOfSquareYards = squareYards; Overloaded
Mutator
}
17
Other Instance Methods
• No need to pass arguments to these
methods –
– Defined in the same class as the data
members
– Instance methods can directly access
private data members
• Define methods as opposed to storing
values that are calculated from other
private data members
public double CalculateAverage( )
{
return (score1 + score2 + score3) /
3.0; 18
}
Property
• Can replace accessors and mutators
• Properties looks like a data field
– More closely aligned to methods
• Standard naming convention in C# for
properties
– Use the same name as the instance
variable or field, but start with
uppercase character
• Doesn’t have to be the same name – no
syntax error will be thrown
19
Property
public double NoOfSqYards
{
get
{
return noOfSqYards;
}
set
{
noOfSqYards = value;
}
}
20
Property (continued)
• If an instantiated object is named
berber, to change the noOfSqYards,
write:
berber.NoOfSqYards = 45;
21
Auto Implemented
Properties
• Do not have to include return or set
statements
– Simply write get; and/or set;
• Do not define separate private data
members
– An anonymous backing field is
automatically created
// Auto-implemented properties
public string Name { get; set; }
public int EmployeeID { get; set; }
22
Auto Properties Initializers
• Introduced with C# 6.0
• Do not define separate private data
members
// Auto-implemented properties
public string TypeOfEmployee
{ get;
} = “Staff”;
23
ToString( ) Method
• All user-defined classes inherit four
methods from the object class
– ToString( )
– Equals( )
– GetType( )
– GetHashCode( )
• ToString( ) method is called
automatically by several methods
– Write( )
– WriteLine( ) methods
• Can also invoke or call the ToString( )
method directly
24
ToString( ) Method (continued)
• Returns a human-readable string
• Can write a new definition for the
ToString( ) method to include useful
details
public override string ToString( )
{ // return string value }
• Keyword override added to provide new
implementation details
• Always override the ToString( ) method
– This enables you to decide what should
be displayed if the object is printed
25
ToString( ) Example
public override string ToString( )
{
return "Price Per Square Yard: " +
pricePerSqYard.ToString("C") +
"\nTotal Square Yards needed: " +
noOfSqYards.ToString("F1") +
"\nTotal Price: " +
DetermineTotalCost( ).ToString("C");
}
26
ToString( ) method
• Sometimes useful to add format
specifiers as one of the arguments to
the Write( ) and WriteLine( ) methods –
Invoke ToString( )
– Numeric data types such as int, double,
float, and decimal data types have
overloaded ToString( ) methods
pricePerSqYard.ToString("C")
27
Calling Instance Methods
• Instance methods are nonstatic method
– Call nonstatic methods with objects – not
classes
• Static calls to members of Math and Console
classes
answer = Math.Pow(4, 2) Console.WriteLine(
);
– Recall can add using statement to reference
static class and then omit class name
• If you need to invoke the method inside
the class it is defined in, simply use
method name
• To invoke method outside class it is
defined in, precede method name with 28
Calling the Constructor
• Normally first method called
• Creates an object instance of the class
ClassName objectName = new
ClassName(argumentList);
or
ClassName objectName;
objectName = new ClassName(argumentList);
• Keyword new used as operator to call
constructor methods
Student firstStudentObject = new Student ( );
Student secondStudentObject = new Student
(“123”, “Traykov”, “Metodi”);
29
Constructor (continued)
• Default
values are
assigned to
variables of
the value
types when
no
arguments
are sent to
constructor
30
Calling Accessor and
Mutator Methods
• Method name is preceded by the object
name
berber.SetNoOfSquareYards(27.83);
WriteLine("{0:N2}",
berber.GetNoOfSquareYards( ));
33
Calling the Constructor
Method
34
Using Public Members
35
StudentApp
39
Resources
C# Coding Standards and Best Practices –
http://www.dotnetspider.com/tutorials/BestPracti
ces.aspx
C# Station Tutorial - Introduction to Classes
–
http://www.csharp-station.com/Tutorials/Lesson0
7.aspx
Object-Oriented Programming –
http://msdn.microsoft.com/en-us/library/dd4606
54.aspx
Introduction to Objects and Classes in C#
http://www.devarticles.com/c/a/C-Sharp/Introduc
tion-to-Objects-and-Classes-in-C-sharp/
40
Summary
• Components of a method
• Class methods
– Parameters
• Predefined methods
• Value- and nonvalue-returning methods
41
Summary (continued)
• Properties
– Auto-implemented
• Instance methods
– Constructors
– Mutators
– Accessors
• Types of parameters
42
Questions?
43