Professional Documents
Culture Documents
PROGRAMMING
LECTURE 8 – OBJECT ORIENTED PROGRAMMING PART 2
PLAN
Static members
Encapsulation
Accessor & Mutators
Properties
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...");
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!
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
using System;
namespace EmployeeApp
{
class MainClass
{
static void Main(string[] args)
{
Employee emp = new Employee();
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
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
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; }
}
public Garage() { }
public Garage(Car car, int number)
{
MyAuto = car;
NumberOfCars = number;
}
}
Unit 1 - Programming / Lecture 8 – Object oriented programming Part 2 24