You are on page 1of 24

UNIT 1 -

PROGRAMMING
LECTURE 8 – OBJECT ORIENTED PROGRAMMING PART 2
PLAN
 Static members
 Encapsulation
 Accessor & Mutators
 Properties

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 2


UNDERSTANDING THE STATIC KEYWORD

A class may define any number of static members using static keyword
o The member must be invoked directly from the class level, not from an object
reference variable
o E.g.,
Console c = new Console();
c.WriteLine("I can't be printed...");
o But instead simply use the class name
Console.WriteLine("Much better! Thanks...");

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 3


UNDERSTANDING THE STATIC KEYWORD

Simply put, static members are


o Items that are deemed (by the class designer) to be so commonplace
o So there is no need to create an instance of the class before invoking the member
While any class can define static members, they are quite commonly found
within utility classes
o By definition, a utility class is a class that does not maintain any object-level state and
is not created with the new keyword
o Rather, a utility class exposes all functionality as class-level members
o Many .NET base class libraries are built this way
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 4
UNDERSTANDING THE STATIC KEYWORD

The static keyword can be applied to the following


o Data of a class
o Methods of a class
o Properties of a class (will study)
o A constructor
o The entire class definition

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 5


DEFINING STATIC FIELD DATA

Instance level data (nonstatic data)


o The object maintains its own independent copy of the data
Static level data (static data)
o The memory is shared by all objects of that category

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 6


ACTIVITY: SAVING ACCOUNT

Create a new Console Application project named


StaticDataAndMembers
Insert a new class into your project named SavingsAccount
Defining
o An instance-level data (to model the current balance)
o A custom constructor to set the initial balance
o A static data named currInterestRate (default: 0.04)

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 7


ACTIVITY: SAVING ACCOUNT This is allocated
once and shared
among all
instances

If the interest rate is modeled instance variable, this would mean every
SavingsAccount object would have its own copy of the currInterestRate field.
Now, assume you created 100 SavingsAccount objects and needed to change the
interest rate. That would require you to call the SetInterestRate() method 100 times!

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 8


DEFINING STATIC METHODS

It’s compiler error to access static member using instance


Let's update the SavingsAccount class to define two static methods
o The first static method (GetInterestRate()) will return the current interest rate
o The second static method (SetInterestRate()) will allow you to change the
interest rate.

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 9


ENCAPSULATION SERVICES

An object's data should not be directly accessible from an object instance.
o Class data is defined as private
o This is accessible indirectly using public members
The problem with public data is that
o The data itself has no ability to "understand" whether the value to assigned to it is valid
Private data could be indirectly manipulated using one of two main techniques
o You can define a pair of public accessor (get) and mutator (set) methods
o You can define a public .NET property

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 10


ENCAPSULATION USING TRADITIONAL
ACCESSORS AND MUTATORS
We will use a case study to demonstrate this
o Create a new project named EmployeeApp
o Add a class named Employee

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 11


using System;
namespace EmployeeApp{
class Employee{
// Field data.

EMPLOYEE.CS private string empName;


private int empID;
private float currPay;
// Constructors.
public Employee() { }
public Employee(string name, int id, float pay){
empName = name;
empID = id;
currPay = pay;
}
// Methods.
public void GiveBonus(float amount)
{
currPay += amount;
}
public void DisplayStats()
{
Console.WriteLine("Name: {0}", empName);
Console.WriteLine("ID: {0}", empID);
Console.WriteLine("Pay: {0}", currPay);
}
}
}
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 12
CANNOT ACCESS PRIVATE MEMBER FROM
OUTSIDE
The empName, empID, and currPay fields are not directly accessible from an
object variable
o Therefore, the following logic in Main() would result in compiler errors:

using System;

namespace EmployeeApp
{
class MainClass
{
static void Main(string[] args)
{
Employee emp = new Employee();

// Error! Cannot directly access private members


// from an object!
emp.empName = "Marv";
}
}
}
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 13
class Employee
{
// Field data.
private string empName;

ACCESSOR & private int empID;


private float currPay;

MUTATOR APPROACH // Constructors.


public Employee() { }
public Employee(string name, int id, float pay)
{
empName = name;
empID = id;
currPay = pay;
}
// Accessor (get method).
public string GetName()
{
This technique requires two return empName;
uniquely named methods to }

operate on a single data point // Mutator (set method).


public void SetName(string name)
{
// Do a check on incoming value
// before making assignment.
if (name.Length > 15)
Console.WriteLine("Error! Name length exceeds 15 characters!");
else
empName = name;
}
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 …….. 14
}
ACCESSOR & MUTATOR APPROACH
using System;

namespace EmployeeApp
{
class MainClass
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Encapsulation *****\n");
// Longer than 15 characters! Error will print to console.
Employee emp2 = new Employee();
emp2.SetName("Xena the warrior princess");

Console.ReadLine();
}
}
} / Lecture 8 – Object oriented programming Part 2
Unit 1 - Programming 15
.NET PROPERTIES APPROACH

.NET languages prefer to enforce data encapsulation state data using


properties
o Properties are just a simplification for "real" accessor and mutator methods
o You are still able to perform any internal logic

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 16


.NET
PROPERTIES class Employee
APPROACH {
private string empName;
private int empID;
private float currPay;

public string Name


{
get { return empName; }
set
{
if (value.Length > 15)
Console.WriteLine("Error! ");
else
empName = value;
}
}
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 17
public int ID
.NET {
get { return empID; }
PROPERTIES set { empID = value; }
}
APPROACH public float Pay
{
get { return currPay; }
set { currPay = value; }
}
// Methods.
public void GiveBonus(float amount)
{
currPay += amount;
}
public void DisplayStats()
{
Console.WriteLine("Name: {0}", empName);
Console.WriteLine("ID: {0}", empID);
Console.WriteLine("Pay: {0}", currPay);
}
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 18
.NET PROPERTIES APPROACH

Properties also are easier to manipulate


o Properties are able to respond to the intrinsic operators of C#
E.g., to add 100 to the current pay
o Using accessor, mutator:
• emp.setPay(emp.getPay() + 100);
o Using properties:
• emp.Pay += 100;

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 19


USING PROPERTIES WITHIN A CLASS DEFINITION

Now, every place within the class that you would like to get/set the data
o You should always use the Properties
o To make sure that the validation/access controls code are executed in not only
outside but also within the class

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 20


READ-ONLY AND WRITE-ONLY PROPERTIES

Read/write only properties


o To configure read-only property just omit the set
o To configure write-only property just omit the get
Example
public string SocialSecurityNumber
{
get { return empSSN; }
}
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 21
UNDERSTANDING AUTOMATIC PROPERTIES

 In some cases you may only need for simple getting and setting the value
o It can be trivial to define private backing fields and simple property definitions multiple times
o You may use automatic property syntax
class Car
{
public string PetName { get; set; }
}

 At compile time, C# compiler will provide


o an autogenerated private backing field
o a fitting implementation of the get/set logic
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 22
UNDERSTANDING AUTOMATIC PROPERTIES

 With the current version of C#


o it is now possible to define a "read-only automatic property" by omitting the set
scope
o It is not possible to define a write-only property
 The class defining automatic properties will always need to use
property syntax to get and set the underlying value
o Why?
o What is good about this?

Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 23


INITIALIZATION OF AUTOMATIC PROPERTIES
class Garage
{
// The hidden backing field is set to 1.
public int NumberOfCars { get; set; } = 1;

// The hidden backing field is set to a new Car object.


public Car MyAuto { get; set; } = new Car();

public Garage() { }
public Garage(Car car, int number)
{
MyAuto = car;
NumberOfCars = number;
}
}
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 24

You might also like