Difference between revisions of "C Sharp Object Oriented Programming"
m (Text replacement - "<hr> <table border=" to "<htmlet>ezoicbottom</htmlet> <hr> <table border=") |
m (Text replacement - "<table border="0" cellspacing="0">" to "<table border="0" cellspacing="0" width="100%">") |
||
Line 1: | Line 1: | ||
− | <table border="0" cellspacing="0"> | + | <table border="0" cellspacing="0" width="100%"> |
<tr> | <tr> | ||
<td width="20%">[[C Sharp Looping with do and while Statements|Previous]]<td align="center">[[C Sharp Essentials|Table of Contents]]<td width="20%" align="right">[[C Sharp Inheritance|Next]]</td> | <td width="20%">[[C Sharp Looping with do and while Statements|Previous]]<td align="center">[[C Sharp Essentials|Table of Contents]]<td width="20%" align="right">[[C Sharp Inheritance|Next]]</td> | ||
Line 247: | Line 247: | ||
<htmlet>ezoicbottom</htmlet> | <htmlet>ezoicbottom</htmlet> | ||
<hr> | <hr> | ||
− | <table border="0" cellspacing="0"> | + | <table border="0" cellspacing="0" width="100%"> |
<tr> | <tr> | ||
<td width="20%">[[C Sharp Looping with do and while Statements|Previous]]<td align="center">[[C Sharp Essentials|Table of Contents]]<td width="20%" align="right">[[C Sharp Inheritance|Next]]</td> | <td width="20%">[[C Sharp Looping with do and while Statements|Previous]]<td align="center">[[C Sharp Essentials|Table of Contents]]<td width="20%" align="right">[[C Sharp Inheritance|Next]]</td> |
Latest revision as of 19:56, 27 October 2016
Previous | Table of Contents | Next |
C# Looping with do and while Statements | C# Inheritance |
Purchase and download the full PDF and ePub versions of this Visual C# eBook for only $9.99 |
So far in C# Essentials we have looked at the basics of programming in C# such as variable types and flow control. Although it would be possible to write a functional program using these techniques, there is much more to becoming a proficient C# programmer. C# is, above all, an object oriented programming language and as such any C# programmer will be expected to create object-oriented applications using this language.
C# provides extensive support for developing object-oriented applications. The subject area of object oriented programming is, however, large. It is not an exaggeration to state that entire books could be dedicated to the subject (because entire books have been dedicated to the subject). As such, a detailed overview of object oriented software development is beyond the scope of C# Essentials. Instead, we will introduce the basic concepts involved in object oriented programming and then move on to explaining the concept as it relates to C# application development.
What is an Object?
Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members.
What is a Class?
Much as a blueprint or architect's drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be.
Declaring a C# Class
Before an object can be instantiated we first need to define the class 'blueprint' for the object. In this chapter we will create a Bank Account class to demonstrate the concepts of C# object oriented programming.
A C# class is declared using the public class keywords followed by the name of the class. Although the C# compiler will accept just about any name for a class, programming convention dictates that a class name begin with a capital letter:
public class BankAccount { }
We have now defined a class which currently contains no members. The next task, therefore, is to add some members.
Creating C# Class Members
Class members or properties are essentially variables and methods embedded into the class. Members can be public, private or protected.
public members can be accessed from outside the object and are also visible in classes derived from the current class. private members can only be accessed by methods contained in the class and are not accessible to derived classes. protected classes are only available to derived classes.
This is the key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters).
We can now extend our BankAccount class to add member variables to hold the account name and number. True to the concept of data encapsulation we will be making some of these members private and writing methods to access these values later:
public class BankAccount { public string accountName; public int accountFee; private int accountBalance; private int accountNumber; }
Now that we have defined the properties of our class we need to look briefly at a few additional data member types, and then learn how to create object instances from the class.
Static, Read-only and Const Data Members
In addition the data member types we have looked at so far, C# also provides support for a number of additional member types.
C# static member types (also referred to as class properties) are used to store data values which are common to all object instances of class. For example, all bank customers would likely earn the same rate of interest on a savings account. An interestRate member would, therefore, be declared as static since it is common across all object instances of the class.
Static members are declared using the static keyword. For example:
public class BankAccount { public static int interestRate; }
Static members are accessed through the class, not though the object. For example we would change the interestRate member for all object instances by reference the BankAccount class as follows:
BankAccount.interestRate = 10;
For data members that must not be modified the const and readonly keywords are provided by C#. Both achieve the same objective of preventing the value assigned to a data member from being changed after it has been declared. The value of a const or readonly member must be assigned at creation time:
public readonly daysInWeek = 7;
Instantiating an Object from a C# Class
The process of creating an object from the class 'blueprint' is called instantiation. The first step is to create an object variable of the required object type. An instance of the object is then created using the new keyword and assigned to the object variable:
BankAccount custAccount; custAccount = new BankAccount();
It is also possible to declare the object variable and assign the object in a single statement:
BankAccount custAccount = new BankAccount();
Now that we have an instance of our BankAccount class the next step is learn how to access the members of the class.
Accessing C# Object Members
Now that we know how to write a class and instantiate objects from the class, we now need to know how to access the members of the object. Firstly, you will recall that we declared some members as being public and others as being private. The public methods are fully accessible from outside the object. This is achieved using something called dot notation. Dot notation is a mechanism by which object members may be accessed by specifying the object and member names separated by a dot (.). For example, to access the accountName member of an object named custAccount we would reference this member using custAccount.accountName:
using System; class Hello { public class BankAccount { public string accountName; public int accountFee; private int accountBalance; private int accountNumber; } static void Main() { BankAccount custAccount = new BankAccount(); custAccount.accountName = "John Smith"; custAccount.accountFee = 5; Console.WriteLine ("Customer Name is " + custAccount.accountName); Console.WriteLine ("Account Fee = $" + custAccount.accountFee); } }
The above code assigns values to the accountName and accountFee members of our object. It then references the properties in order to display text which reads:
Customer Name is John Smith Account Fee = $5
This approach works well for public class members, but not for private members. An attempt, for example, to use dot notation to access the private accountNumber member will result in a compilation error along the the lines of:
error CS0122: 'Hello.BankAccount.accountNumber' is inaccessible due to its protection level
In order to access private members we need to provide access methods in the class.
Adding Methods to a C# Class
Class method members are sections of code contained in a class which can be called from outside an object to perform specific tasks. Common types of methods are getter and setter methods which are used to access private data members of a class. For example, we can declare a getter and a setter method to get and set the protected accountNumber member:
public class BankAccount { public string accountName; public int accountFee; private int accountBalance; private int accountNumber; public int getAccountNumber() { return accountNumber; } public void setAccountNumber(int newNumber) { accountNumber = newNumber; } }
Class methods are called using dot notation. For example, to set the value of the accountNumber:
BankAccount custAccount = new BankAccount(); custAccount.setAccountNumber( 12345 ); Console.WriteLine ("Account Number = " + custAccount.getAccountNumber() );
The above code sets the account number using the setter method and then displays the account number using the getter method.
Now that we have looked at method class members the next task is to look at two special class methods, constructors and finalizers.
C# Constructors and Finalizers
Despite the grand sounding names, C# class constructors and finalizers are nothing more than methods which get called when an object is instantiated and destroyed. The constructor is particularly useful for allowing initialization values to be passed through to an object at creation time. Let's say that we would like to be able to initialize the accountName and accountNumber members at the point that we initialize the custAccount object. To do so we need to declare a constructor.
Constructors are declared the same way as other methods with the exception that the name of the method must match the class name:
public class BankAccount { public string accountName; public int accountFee; private int accountBalance; private int accountNumber; // Constructor public BankAccount(string acctName, int acctNumber) { accountName = acctName; accountNumber = acctNumber; } // .... }
We can now use the constructor to initialize these members at object creation:
BankAccount custAccount = new BankAccount("Fred Wilson", 123456);
Finalizers are used to clean up any resources used by a class object when the object is destroyed. Unlike constructors which can be triggered from code using the new keyword there is no way to explicitly call a finalizer (for example there is no delete equivalent to the new keyword). Instead, the finalizer will be called when the garbage collector decides that the object instance is no longer needed. All the programmer can be sure of is that the finalizer will be called at some time between the when the object is no longer needed by the code and the point that the application terminates.
Finalizers are defined in the same way as constructors with the exception that the name is preceded by a tilde (~):
// Finalizer public ~BankAccount(string acctName, int acctNumber) { // Code to perform clean up }
Purchase and download the full PDF and ePub versions of this Visual C# eBook for only $9.99 |
Previous | Table of Contents | Next |
C# Looping with do and while Statements | C# Inheritance |