You are on page 1of 62

Introduction to Classes and Objects

Introduction
Syntax of a class
Syntax of a class Access Modifiers
Members of a class

Constructors
Destructors
Fields
Constants
Methods
Property

Passing parameters to Methods


Namespace
Class Examples
1

Building Blocks of C# Application


Object Oriented Programming along with user defined Types play
a central role in developing C# applications
A C# application is a an assembly. It can be an executable (exe)
or a library (dll)
Typically, a C# program file contains classes, methods and types

Solution contains Projects


Projects contains files
File contains Class and/or Types
Classes contains methods
and/or Types
Files in Project are compiled
into an assembly
In a solution, there can be
many projects (and assemblies)
An application consists of one
or more assemblies

Assembly
Project
Project
File
File
Classes
File
File
Classes
& TypesFile
Classes
Classes
& Types
File
Classes
&
Types
& Types
Classes
& Types
& Types
2

Introduction - Content of an
Application
C# applications contain one or more classes
C# applications can span across many files
All applications have a starting point.
Function Main is the starting point of a C#
Console application and must be in one of
the classes
You can put a Main in every class. If so, then
you must specify which main function is the
starting point of your application. This is
commonly done to test a class
Unlike Java, the file name does not have to
be name of the class that contains the main
function
3

Classes, Methods, Functions


Program Design
Before you start to code, design your application
Understand the requirements
Identify parts of the program that are logically
independent and can be coded and tested a piece

Construct your program from smaller pieces or


components
Each piece will be more manageable than the
whole original program
Test each piece individually, before testing the
whole application

Methods and Classes


Methods (or Functions) and classes
A unit of code (program) that does a specific thing
Functions are also known as procedures or
methods. Classes may have some similarities to a
method, but are very different
There are hundreds of predefined classes and
methods available for use

Benefits of using methods and classes

Easy to write code


Allows reuse of code, which saves time and effort
Easy to maintain, debug and test
Easy to look and understand what the code is doing

Common Terms in
Object Oriented Programming
Polymorphism

From Greek - meaning many forms.


It is the quality that allows one interface to be used for a
general class of action

Abstraction Information Hiding

Hiding all details except those that need to be exposed


Implementation details are hidden within the classes
themselves. Only the interface is exposed

Encapsulation

Combining code and data

Inheritance

Inherit properties from the parent (base) class and can


have its own properties

What is a Class?
Class is the standard unit of programming in C#
It is like a blueprint or template contains all
the information about the type
Objects are instantiated (created) from a class
An object is an (unique) instance of a class
For example, a house (object) is an instance of a
blueprint (class). Each house is a separate
entity, but can be made from the same blueprint
Another analogy. When you create a variable,
the type (for example int) can be considered
as the class and the variable would be the
object. You first create an object of a type (class)
and then work with the object (in most cases)

Syntax of a Class
[attributes] [modifiers] class identifier
[:baselist]
{class body}[;]

For now, we will skip the attributes, modifiers and the baselist
A Class (body) consists of fields (types), properties and
methods
Types can be primitive types or user defined types
Types can be value or reference types
A Class can contain nested classes or use other classes as
types
C# applications must contain one or more classes
A C# class is not restricted to a single file (unlike C++, like
Java). They span across multiple files. This requires attaching
a partial attribute to the class

A Simple Class Example


public class AClass
{
// ****** field or an instance variable. A variable
// shared by all methods of this class
int var1;
// ****** methods - Constructor
public AClass() { some code };
// ****** method General
public void DisplayMessage( string courseName )
{
Console.WriteLine(Grade book for\n{0}!",courseName );
} // end method DisplayMessage
} // end class GradeBook

A Simple Class

Keyword public is an access modifier. Access modifiers determine the


accessibility of a class, properties and methods.

2009 Pearson Education, Inc. All rights reserved.

10

Members of a Class

Constructors
Destructors
Constants
Fields
Methods
Properties
Indexers
Operators
Events
Delegates
Classes
Interfaces
Structs

11

Members of a Class
Instance Variables and Properties
Variables declared in the body of a method are
known as local variables
When a method terminates, the values of its
local variables are lost
Variables declared in the body of a class, outside
the methods are known as instance variables
(also known as attributes or fields) are
represented as variables in a class declaration
Each object has its own copy of instance
variables, but methods are shared by all objects

12

Instance Variables and Properties (Core)


Instance Variables (also known as Fields or
Attributes)
Member of the class that holds data
Instance data type can be user defined or built in type. Each
object will have its own copy of this variable
Can be value or reference type
Can be primitive data types, user defined types, arrays,
interfaces or references to objects
Can be a simple or readOnly variable, or a constant (static
readOnly)
Have an access specifier that determines its scope. If not
specified, by default, it is private
Have default values which are assigned before the constructor
is called
For numeric, it is 0
For boolean, it is false
For reference, it is null

13

Hands on lab, Class Example


// Fig. 4.4: GradeBook.cs
// Class declaration with a method that has a parameter.
// Does not have any constructors or Main method
using System;
public class GradeBook
{
// display a welcome message to the GradeBook user
public void DisplayMessage( string courseName )
{
Console.WriteLine(Grade book for\n{0}!",courseName );
} // end method DisplayMessage
} // end class GradeBook

14

Hands on lab, Class Example


// Fig. 4.5: GradeBookTest.cs from Deital & Deitel
using System;
public class GradeBookTest
{
// Main method begins program execution
public static void Main( string[] args )
{
// create a GradeBook object & assign it to myGradeBook
GradeBook myGradeBook = new GradeBook(); //create class
// prompt for course name and read it
Console.Write ("Please enter the course name: " );
string nameOfCourse = Console.ReadLine(); // read text
Console.WriteLine(); // output a blank line
// call myGradeBook's DisplayMessage method
myGradeBook.DisplayMessage( nameOfCourse );
} // end Main
} // end class GradeBookTest

15

UML Diagram
Unified Modeling Language (UML)
A standard, general-purpose modeling language used in
software engineering for designing software
It uses a set of graphical notations to create an abstract model
of a specific system

Classes are modeled as a rectangle with three


compartments
The top compartment contains the name of the class
The middle compartment contains the classs
attributes
The bottom compartment contains the methods

Fig. 4.6 UML class diagram, + indicates


that the class GradeBook has a public
DisplayMessage method with a
courseName parameter of type string.

16

Namespace in Class
Classes in the same project are considered to be
in the same namespace
using indicates that the application uses classes
in another namespace
Without using, we would have to write the fully
qualified class name
System.Console.WriteLine ( "Please enter the course
name:" );

17

Members of a Class - Properties

Properties
Contain special methods called get and set, to
access classs (private) data. These methods are
also known as accessor methods
Get allows you to read back the value of the fields
Set allows you to write data to the fields
Properties simulate (looks and act like) public fields.
This enables data to be accessed easily while still
providing the safety and flexibility of methods
Properties can be
Read-only Only contains a get method
Write-only Only contains a set method
Read-write Contains both get and set methods

18

Members of a Class - Properties


The get and set methods (accessors) can have a
different access specifier for each. The default is
the access specifier of the entire property
Example: Get can be public while Set is private
<AccessSpecifer> <Ret Type> <Property Name>
{
// reads or gets the data from the field
get
{
return < field name >;
} // end get
//write to or set data in the field, private is optional
[private] set //Default is accSpc for the whole property
{
< field name > = value; // value is a keyword
} // end set
} // end property LastName

19

Example of Fields and Properties


Syntax of Property
[attribute] <Access specifier> < data type> <property name>
{Body}
using System;
public class Employee
Field
{
private string name;
// read-write property that gets and sets the last name
public string Name
Property
{
Name
get
{
Property
return name;
} // end get
private set
value is a keyword
{
name = value;
} // end set
} // end property LastName
} // end class Employee

20

Example of Field and Property


using System;
// Fig. 4.7: GradeBook.cs
public class GradeBook
Field or Instance variable
{
private string courseName; // course name for this GradeBook
// property to get and set the course name
public string CourseName
{
Property Name
get
{
return courseName;
} // end get
set
value is a keyword
{
courseName = value;
} // end set
} // end property CourseName
public void DisplayMessage()
{
Console.WriteLine( "Welcome to the grade book");
}
// end method DisplayMessage
} // end class GradeBook

21

Auto-implemented Properties
Auto-implemented properties were introduced in
C# Version 3.0. Following is the old syntax (C#
private
string courseName; // course name for this GradeBook
V2.0)
// property to get and set the course name
public string CourseName
{
get
{
return courseName;
} // end get
set
{
courseName = value;
} // end set
} // end property CourseName

Field
Property
Name

New syntax in C# Version 3.0.


public string CourseName { get; set;}

22

Example of Field and Property


// Fig. 4.8: GradeBookTest.cs
Use of
using System;
Property
public class GradeBookTest
{
// Main method begins program execution
public static void Main( string[] args )
{
// create a GradeBook object and assign it to myGradeBook
GradeBook myGradeBook = new GradeBook();
// display initial value of CourseName
Console.WriteLine( "Initial course name is: '{0}'\n",
myGradeBook.CourseName );
// prompt for and read course name
Console.WriteLine( "Please enter the course name:" );
myGradeBook.CourseName = Console.ReadLine(); // set CourseName
Console.WriteLine(); // output a blank line
// display welcome message after specifying course name
myGradeBook.DisplayMessage();
} // end Main
} // end class GradeBookTest

23

4.6UML Class Diagram with a


Property
Figure4.9 contains an updated UML class diagram for the
version of class GradeBook.
We model properties in the UML as attributes preceded by
the word property in guillemets ( and ).
To indicate that an attribute is private, a class diagram
would list the private visibility symbol a minus sign ()
before the attributes name.

Fig. 4.9 | UML class diagram indicating that class GradeBook has a public CourseName
property of type string and one public method.

24

Members of a Class - Methods


Methods

A method is a block of code (data and statements)


In C#, code can only execute inside a method
Methods can receive data as a list of arguments
Methods have a type, a name (identifier) and optionally, a
list of parameters enclosed inside a parenthesis and
separated by commas. If there are no values inside the
parenthesis, it means that the method does not take any
input
The type of data return by the method must be the same as
the type of the method
Methods parameters and variables inside a method can only
be accessed by that method (SCOPE OF VARIABLES)
Variables declared outside of the methods of a class are
called fields or instance variable and are accessible by all
members of the class
All methods can use the fields of their class

25

Members of a Class - Methods


Methods
Methods must be declared within a class or struct
Methods also have access modifiers
A typical method receives data as input, processes the data
and returns a values. Some methods simply perform tasks;
they dont receive any input nor do they return any value

A Typical Method or Function


Input
May receive input as a list of parameters

Processing
Processes the input or performs some action (execute code)

Output or Result
May return data as a result of processing the information

26

Members of a Class - Types of


Methods
Types of Methods
Main
Starting point of all Console Applications. Its name is always
Main
You can put a Main in any class, but then you have to specify
which is the starting point of your application

Constructors
Destructors
Operators (Discussed in advanced topics)
General Purpose Methods

27

Members of a Class - Constructors


Constructors
A special method in the class
Whenever an object of a class (or struct) is created,
the classs constructor (method) is called
A class (or struct) may have multiple constructors
as long as they take different arguments
Allows you to set default values, validate and set
values, or initialize data for that object
If you do not provide a constructor, C# will create a
parameterless constructor by default and it will set
all member variables to their default values
If you specify any constructor, no default
constructor is provided

28

Members of a Class - Destructors


Destructors
A special method of the class that is called when the
object goes out of scope (or is destroyed)
Typically used for releasing resources or saving
information before the object is destroyed
Has the same name as the class, except that it is
preceded by a ~ character
A class can only have one destructor
A destructor does not take parameters, nor does it return
any value
Destructors cannot be inherited or overloaded
Destructors should NOT be called by your program. They
are invoked automatically by the Garbage Collector to
perform termination housekeeping before releasing
memory

29

Types of Methods - Destructor


Destructors
No guarantee when or if GC will call the
destructor. Therefore dont use a destructor
in C# (or Java) unless you have a real good
reason to do so
Object becomes eligible for garbage collection
after GC (Garbage Collector) invokes the
destructor
Since C# does most of the house keeping
for you, you may not need a destructor
Empty destructors should not be used

30

Constructor, Destructor - Example


class Car
{
int numOfDoors; //field, can access by the whole class
string model
Car()
// Constructor
{
// statements...
}
Car(string mod, int nd) // Constructor - takes 2 args
{
model = mod;
// statements...
numOfDoors = nd;
}
~Car()
// destructor
{
// cleanup statements...
}
}

31

Types of Methods - Constructors


public class Time
{
private int hour;
private int minute;
private int second;

***** THESE ARE FIELDS *****

// Time no-arg constructor: initializes each instance


public Time()
{
hour = 0;
// no need to do this C#,
minute = 0; // all vars are automatically initialized
second = 0;
}
// Time constructor: hour supplied, minute & second = 0
public Time(int h )
{
hour = h;
minute = 0;
second = 0;
}

32

GradeBook class with a custom


constructor

Fig. 4.14 | GradeBook class with a constructor to initialize the course


name. (Part 1 of 2).

2009 Pearson Education, Inc. All rights reserved.

33

GradeBook class with a custom


constructor

Fig. 4.14 | GradeBook class with a constructor to initialize the course


name. (Part 2 of 2).

2009 Pearson Education, Inc. All rights reserved.

34

Figure 4.15 demonstrates initializing GradeBook


objects using the constructor.

Fig. 4.15 | GradeBook constructor used to specify the course name at the time each
GradeBook object is created. (Part 1 of 2).

2009 Pearson Education, Inc. All rights reserved.

35

Fig. 4.15 | GradeBook constructor used to specify the course name at the time each
GradeBook object is created. (Part 2 of 2).

2009 Pearson Education, Inc. All rights reserved.

36

Initializing Objects with


Constructors
The UML class diagram models class GradeBook.
To distinguish a constructor from other operations, the
UML places the word constructor between guillemots
( and )

Fig. 4.16 | UML class diagram indicating that class GradeBook has a constructor with a name
parameter of type string.

2009 Pearson Education, Inc. All rights reserved.

37

Floating-Point Numbers and


decimals
Types float and double are called floating-point types
C# treats all real numbers you type in an applications
source code (such as 7.33 and 0.0975) as double values
decimal variables store a limited range of real numbers,
but are more precise and better suited for monetary
amounts
To type a decimal literal, you must type the letter M or
m at the end of a real number

Common Programming Error 4.3


Using floating-point numbers in a manner that assumes they are
represented precisely can lead to logic errors.

2009 Pearson Education, Inc. All rights reserved.

38

Account (Fig.4.17)
An instance variable represents
each Accounts own balance.

The constructor receives a


parameter that represents the
accounts starting balance.

Method Credit receives


one parameter named
amount that is added to
the property Balance.

Fig. 4.17 | Account class with a constructor to initialize instance


variable balance. (Part 1 of 2).

2009 Pearson Education, Inc. All rights reserved.

39

Balances get accessor returns


the value of the Accounts
balance.

Balances set accessor


performs validation to
ensure that value is nonnegative.

Fig. 4.17 | Account class with a constructor to initialize instance


variable balance. (Part 2 of 2).

2009 Pearson Education, Inc. All rights reserved.

40

AccountTest (Fig. 4.18) creates two Account objects and


initializes them with 50.00M and -7.53M (decimal literals).

Passing an initial balance


which will be invalidated by
Balances set accessor.

Outputting the Balance


property of each Account.
2009 Pearson Education, Inc. All rights reserved.

41

Local variable
depositAmount is
not initialized to 0
but will be set by
the users input.
Obtaining input
from the user.

Obtaining the
deposit value
from the user.

2009 Pearson Education, Inc. All rights reserved.

42

Outputting the
balances of
both Accounts.

2009 Pearson Education, Inc. All rights reserved.

43

Floating-Point Numbers and Type


decimal

44

A value output with the format item {0:C} appears as


a monetary amount.
The : indicates that the next character represents a
format specifier.

2009 Pearson Education, Inc. All rights reserved.

44

45

Format Specifiers

Fig. 4.19 | string format specifiers.

2009 Pearson Education, Inc. All rights reserved.

45

Example 4.16
public class AccountTest
{
public static void Main( string[] args )
{
Account account1 = new Account( 50.00M ); // create Account object
Account account2 = new Account( -7.53M ); // create Account object
// display initial balance of each object using a property
Console.WriteLine( "account1 balance: {0:C}",
account1.Balance ); // display Balance property
Console.WriteLine( "account2 balance: {0:C}\n",
account2.Balance ); // display Balance property
decimal depositAmount; // deposit amount read from user
// prompt and obtain user input
Console.Write( "Enter deposit amount for account1: " );
depositAmount = Convert.ToDecimal( Console.ReadLine() );
Console.WriteLine( "adding {0:C} to account1 balance\n",
depositAmount );
account1.Credit( depositAmount ); // add to account1 balance

2009 Pearson Education, Inc. All rights reserved.

46

Example 4.16
// display balances
Console.WriteLine( "account1 balance: {0:C}",
account1.Balance );
Console.WriteLine( "account2 balance: {0:C}\n",
account2.Balance );
// prompt and obtain user input
Console.Write( "Enter deposit amount for account2: " );
depositAmount = Convert.ToDecimal( Console.ReadLine() );
Console.WriteLine( "adding {0:C} to account2 balance\n",
depositAmount );
account2.Credit( depositAmount ); // add to account2 balance
// display balances
Console.WriteLine( "account1 balance: {0:C}", account1.Balance );
Console.WriteLine( "account2 balance: {0:C}", account2.Balance );
} // end Main
} // end class AccountTest

2009 Pearson Education, Inc. All rights reserved.

47

Overloaded Methods
If a method has the same name and a different
signature, it is considered as an overloaded
method
Each method must have the same name but it
must also be unique. This true if
Number of parameters are different
Type of parameters are different
Return type does not matter

In the example below, method Time (constructor


from previous example) is overloaded
public
public
public
public

Time()
Time(int h )
Time(int h, int m )
Time(int h, int m, int s )

48

Passing Parameters to Functions


Information is passed to methods via arguments or
parameters
Constructors and destructors do not return any
value
Destructor does not take any parameters
General purpose methods can take parameters
and return (only one ) a value
Another way to get more information back from a
function is to pass information by reference
By default, most primitive data passed to a
function is passed by value. Array are passed by
values.
Passing large amount of data by value is inefficient

49

Passing parameters, Reference Vs


Value
Passing Information to a Function by Value
The value of the variable is passed to the function. The
function must declare a new variable to hold this value
This new variable is declared in the argument list of the
function. Its scope is limited to this function and is destroyed
as soon as the function is done executing the code

Passing Information to a Function by Reference


The address of the variable is passed to the function. The
function must declare a new variable (a pointer or reference
type, that holds and address instead of data) to hold this
address
This new variable is declared in the argument list of the
function. Its scope is limited to this function and is destroyed
as soon as the function is done executing the code

50

Passing parameters, Reference Vs


Value
The Big Difference
When data is passed by value to a function, it is
stored in a variable that belongs to the function. Any
changes that are made, are made to the local
variable and there is no impact to the original
variable in the calling program
When data is passed by reference to a function, the
function receives the memory address of where
original variable is located. The function has a new
variable, but it is pointing to the same memory
address of the variable in the main program. The
new local variable becomes an alias to the original
variable (two names for the same memory location).
Any made to the local variable will is same as modify
the original variable.

51

Reference Vs Value - System.Object


System.Object
System.ValueType
System.Array
System.String
System.Exception
System.Interface

Struct
System.Enum
Primitive Types (13)
Boolean

int

Byte

Single

Decimal

Double

User Defined
System Defined

Value types can be 13 primitive types, structs and enums


Figure 2-2 Hierarchy of common reference and value types (Core C#)

52

Namespaces
Namespaces

Class are contained inside a namespace


Namespace can be nested

namespace NSpace1
{

class C1
{
class C2
{
}
}
namespace NSpace2
{
class C2
{
}
}
}

// NSpace1.C1
// NSpace1.C1.C2

// NSpace1.NSpace2
// NSpace1.NSpace2.C2

53

Class - Programming Practices


Precede every field and method declaration with
an access modifier. Makes the code
Easy to read
Less chance of making a mistake
Portable in future

Keep fields together, either in the beginning of the


class or at the end. Makes it easy to read the code
By default all fields are private
All or most fields should be private
All or most properties should be public
For class name, use a noun or noun phrase. Use
Pascal case (first letter capital). Do not prefix the
name with C

54

Nested Namespaces
Example of nested namespaces
Needed when more than one class names have
to be same or when you class name is in conflict
with a system class name
using NSpace1;
C1 a;
NSpace1.C1 b;

// The NSpace1. is implicit


// Fully qualified name

C2 c;
NSpace1.NSpace2.C2 d;
C1.C2 e;

// Error! C2 is undefined
// One of the C2 classes
// The other one

55

Namespace Using Statement


The using statement also lets you create aliases
using C1 = N1.N2.C1;
using N2 = N1.N2;
C1 a;
N2.C1 b;

// Refers to N1.N2.C1
// Refers to N1.N2.C1

Best practice: Put all of your types in a unique


namespace
Have a namespace for your company, project,
product, etc.
Look at how the .NET Framework classes are
organized

56

Syntax of a Class Access


Modifiers
[attributes] [modifiers] class identifier
[:baselist] {class body}[;]
Specifies Accessibility (Scope or visibility)
A Classs access modifier indicates if the class is accessible from
other assemblies, from same assembly, from a containing class
or a derived class
The scope of an object, method or class refers to its accessibility
and visibility. It also refers to the lifetime of an object (like vars)
Top-level types (those directly in a namespace) can be public or
internal (classes)
A class can have public, protected, internal, private and
protected internal as its access modifier (also called access
specifier)
Class members can be public, private, protected, internal
Struct members can be public, private or internal (no
inheritance)

57

Access Modifiers for a Class


Access
Specifier

Access

Public

A class can be accessed from any assembly

protected

Allows access to members of the class or type and classes or


types that are derived from it. Also allows access to nested class

Internal

To all code within the assembly. This applies to methods and data
too. If methods and fields are declared internal, they are also
accessibly throughout the code in the assembly (Like public, but
access is limited to the assembly and not derived classes).
This is default.

private

Members of the class or Type only

protected
internal

To members of the current class, members of classes or Types


that are derived from it within the whole assembly

58

Access Modifiers for Fields


Like Classes, Access Modifiers also apply to fields

If the access
modifier is

Then this member is accessible

public

to everyone

private

Only the member of this class. Not even to members of


the object created from this class

protected

to members of this class and classes derived from this


class within this assembly

internal

to everyone in current assembly

59

Field Modifiers
Besides the Access Modifiers, a field can have
two additional modifiers
Static (like constant)
The field is part of the class and not the instance of the
class (object). It is accessed by specifying
classname.fieldName and NOT by objectname.fieldName

Readonly (per instance)


Similar to a constant, except that it does not have to be
initialized when it is declared (although it can be). It can
be initialized in the constructor. An attempt to modify this
field later will result in a syntax error

60

Summary of accessibility
Class can be
accessed by
classes in:

Access Modifiers

Public

Protected

Internal

Private

Another assembly

Yes

N/A

No

N/A

Same assembly

Yes

N/A

Yes

N/A

Containing assembly

Yes

Yes

Yes

Yes

Class derived from


containing class

Yes

Yes

Yes

No

61

Access Modifiers and Scope


Guidelines
Keep Classes public
The scope of the class itself can be specified as public
or internal

Keep Fields private


Make scope as restricted as possible for Fields and
utility methods.
Create public Properties to set and access content of a
field
Too many Properties can slow down an application.
Trade off between keeping Fields private and use of
modifiers

62

You might also like