0% found this document useful (0 votes)
5 views

Lecture 03 - Class, Object

Uploaded by

ahihihi.0602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 03 - Class, Object

Uploaded by

ahihihi.0602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Introduction to Classes, Objects,

Methods and strings


Outline
• Classes, Objects, Methods, Properties and Instance Variables
• Declaring a Class with a Method
• Instantiating an Object of a Class
• Declaring a Method with a Parameter
• Instance Variables and Properties
• UML Class Diagram with a Property
• Software Engineering with Properties and set and get Accessors
• Auto-Implemented Properties
• Value Types vs. Reference Types
• Initializing Objects with Constructors
• Floating-Point Numbers and Type decimal
A car example
• Real-life example: a car
– A car typically begins as engineering drawings
– These include design for an accelerator pedal
– The pedal “hides” complex mechanism behind
– This enables people with little or no knowledge of
how engines work to drive a car easily
– However, you can’t drive the drawings
Methods
• Performing a task in an app requires a method
• The method describes the mechanisms (statements) that actually
perform the tasks
• The method hides from its user the complex task it performs
• This is a typical signature of a method
<accessModifier> <returnType|void> methodName([param1, param2…]){
//Code comes here
}
Example
public void DisplayMessage(string name){
//code comes here
}
Classes
• In C# we begin by creating an app unit called a
class to house (among other things) a method
• E.g., a class represents a bank account might
contain
– one method to deposit money in an account,
– one method to withdraw money
– one method to inquire current balance
• Typical class declaration
<accessModifier> class <ClassName>{
//Attributes and methods here
}
Objects
• Just like you cannot drive a drawing, you can’t
“drive” a class
– You must build a car, in C# means you must create
an object of a class before using it
– That is the reason C# is called OO language
• Typical syntax to create an object is
– ClassName objectName = new ClassName([args]);
Method Calls
• When you drive a car, pressing its pedal sends
a message to the car to perform a task
• Similarly, you send messages to an object –
each message is known as a method call
– To tell the called method to perform its task
Attributes
• In addition to a car’s capabilities, it also has many attributes
– Its color, Number of doors, Amount of gas in its tank, etc
– Every car maintains its own attributes e.g., a car knows how much it
has in its own tank, but not that of another car
• Similarly, an object has attributes that are carried with the object as
it’s used in an app
– These attributes are specified as part of the object’s class
• Example, a bank account object has
– Balance attribute
– Each account object knows its own balance, not that of the other
accounts
• Attributes are specified by the class’s instance variables, its typical
declaration is as following
– <accessModifier> <dataType> varName;
Properties, get and set Accessors
• Notice that these attributes are not necessarily
accessible directly
– Drivers should not take apart the car’s engine to
observe the amount of gas in its tank
– Driver can check that on the dashboard
• Similarly, you do not need to have access to an
object’s instance variables in order to use them
– You should use properties of an object
– Properties contain get accessors (to read value) and
set accessors (to store value)
Properties, get and set Accessors
class Student
{
private string name;//instance variable
public string Name{//Property
get {//getter
return name;
}
set {//setter
name = value;
}
}
}
Activity: Class and Method
• Create a project called GradeBookTest
• Create a new class called GradeBook
• GradeBook will display welcome message
• Create an object of GradeBook in the Main
Creating new project

1 2

1. Click File > New


2. Click Project
3. Select Console App
4
4. Input project name
5. Click OK
5
Adding GradeBook class
1

3 4 5

1. Select solution explorer


2. Right click on the
project
3. Click Add
4. Click New Item…
5. Select Class
6. Input class name
7. Click Add
6
7
Class and Method
namespace GradeBookTest
{
class GradeBook
{
public void DisplayMessage() {
System.Console.WriteLine("Welcome to GradeBook");
}
}
}

namespace GradeBookTest
{
class Program
{
static void Main(string[] args)
{
//creating new object
GradeBook gradeBook = new GradeBook();
gradeBook.DisplayMessage();//method call
}
}
}
UML Class Diagram for GradeBook
• In UML a class is modelled as a rectangle with
three compartments
– The first one contains the name (bold)
– The middle one contains attributes (instance
variables and properties)
– The bottom one contains class’s operations
(methods)
Declaring Method with Parameters
• The Analogy:
– The car’s gas pedal sends a message to the car to perform
a task – to go faster
– But how fast should it be, we need to inform it
• Method can require one or more parameters
– They represent additional info to perform the task
– Parameters are separated by commas
– E.g., public void DisplayMessage(string p1, string p2)
• Method call can supply the values
– These are called arguments – for each of the parameters
– E.g., obj.DisplayMessage(“Mr. A”, “Ms. B”);
Method with Parameter
namespace GradeBookTest
{
class GradeBook
{
//courseName is a parameter of type string
public void DisplayMessage(string courseName) {
System.Console.WriteLine("Welcome to GradeBook for {0}", courseName);
}
}
}
namespace GradeBookTest
{
class Program
{
static void Main(string[] args)
{
//creating new object
GradeBook gradeBook = new GradeBook();
//courseName is a variable to store the input course
System.Console.WriteLine("Please input course name: ");
string courseName = System.Console.ReadLine();
//courseName is used as an argument (value for the param)
gradeBook.DisplayMessage(courseName);//method call
System.Console.ReadLine();
}
}
}
Class diagram with method
parameters

Parameter name And its data type


GradeBook class with Instance Variable
and Properties
namespace GradeBookTest
{
class GradeBook
{
private string courseName;

public string CourseName


{
get { return courseName; }
set { courseName = value; }
}

//courseName is a parameter of type string


public void DisplayMessage() {
System.Console.WriteLine("Welcome to GradeBook for {0}!", CourseName);
}
}
}
Program
namespace GradeBookTest
{
class Program
{
static void Main(string[] args)
{
//creating new object
GradeBook gradeBook = new GradeBook();
System.Console.WriteLine("Initial name is: {0}.", gradeBook.CourseName);
System.Console.WriteLine("Please input course name: ");
gradeBook.CourseName = System.Console.ReadLine();
//courseName is used as an argument (value for the param)
gradeBook.DisplayMessage();//method call
System.Console.ReadLine();
}
}
}
Access modifier public and private
• private members are accessible only to members of
the same class
– E.g., in previous example courseName can be access by
CourseName (property) and DisplayMessage method only.
– Declaring instance variable with private modifier is called
information hiding (or encapsulation)
• public members are accessible everywhere
– E.g., in previous example CourseName (property) and
DisplayMessage method are declared as public
• General principle is that
– Instance variables are declared as private
– Properties and Methods are declared public
Class diagram with a property
+ means this is public <<property>>: indicating this is a property
property name
property data type

Note:
You could also model (optional) the private instance variable, and so, you can add
this to the middle section
- courseName: string
The ‘-’ sign indicates that it is the private member
The courseName is the name of the variable
string is the data type
Software Engineering with get/set
• It seems like get/set is the same as making its
corresponding instance variable public
• This is not the case because
– They allows the class to control the manner in which
the data is set/get
– So we can validate the data
• We should always manipulate data within the
class via the class properties
– Even the class itself can have direct access to the
instance variable
Auto-implemented properties
• When set simply assign the value and get simply
return the value
– No logics appear in the accessors
– C# provides auto-implemented properties
• This is handy when you first create the class
– You can modify this when needing to add logics
• So we can implement the CourseName property
with this
– public string CourseName {get; set}
– The code snippet is “prop” then a “Tab” key twice
VALUE-TYPES VS. REFERENCE-TYPES
Value Types
• C#’s simple types (like int and double) are
value types
– Variable of value type contains value of that type
Reference Types
• Reference-type variable (sometimes called
reference)
– Contains the address of a location in memory
where the data is stored
Reference-type instance variable
initialized to null
• Reference-type instance variables (such as
myGradeBook) are initialized by default to null
• string is a reference type
• an Empty string is different from a null
– Empty string refers to a string with no character
– null refers to nothing
Send messages to object
• A client of an object must use variable that refers
to the object to
– invoke (i.e., call) the object’s method
– access the object’s properties
• In our example
– Main method uses myGradeBook to send messages to
the GradeBook object
– The messages are calls to methods or references to
properties
– E.g., myGradeBook.CourseName =
Console.ReadLine();
CONSTRUCTORS
Initializing objects with constructors
• The GradeBook object is created
– Its instance variable courseName is initialized to null
by default
• How if we would like to provide a name for the
courseName variable?
– That is when we need to use constructor
• Constructor
– Is called automatically when creating a new object
– Has the same name as the class name
– Default there is a constructor with no input parameter
– We can specify the parameters for the constructor
GradeBook Class with Constructors
namespace GradeBookTest
{
class GradeBook
{
public GradeBook(string courseName)
{
CourseName = courseName;
}
public string CourseName { get; set; }
//courseName is a parameter of type string
public void DisplayMessage() {
System.Console.WriteLine("Welcome to GradeBook for {0}!", CourseName);
}
}
}
Program
namespace GradeBookTest
{
class Program
{
static void Main(string[] args)
{

System.Console.WriteLine("Please input course name: ");


//courseName is a variable to store the input course
string courseName = System.Console.ReadLine();
//creating new object
GradeBook gradeBook = new GradeBook(courseName);
//courseName is used as an argument (value for the param)
gradeBook.DisplayMessage();//method call
System.Console.ReadLine();
}
}
}
Updating the UML class diagram with
a constructor
Activity: Develop Account Class
• Develop Account class
– With balance of type decimal (why?)
– As the UML class diagram shown in next page
• Develop the program
– To test the Account class as shown in the next two
pages
UML class diagram for Account class
Program sample output
References
Deitel, P. & Harvey, D., 2013. C# 2012 for
Programmers. 5th ed. Prentice Hall.

You might also like