Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
What is an Object?
An object is a self-contained piece of functionality that can be easily used, and reused as the building blocks for a software application. 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:
}
We have now defined a class which currently contains no members. The next task, therefore, is to add some members.
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 Our object. It then references the properties in order to display text which reads:
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.
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 (~):
What is Inheritance?
The concept of inheritance brings something of a realworld view to programming. It allows a class to be defined which has a number of characteristics and then other classes to be created which are derived from that class. The derived class inherits all of the features of the parent class and typically then adds some features of its own. By deriving classes we create what is often referred to as a class hierarchy. The class at the top of the hierarchy is known as the base class and the derived classes as subclasses. Any number of classes may be derived from a class. It is only possible for a derived class to inherit from one class. As such, C# is known as a single inheritance programming language. Classes need not only be derived from a base class. For example, a subclass can also inherit from another subclass.
An Example of Inheritance
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; } }
This class does a good job of defining characteristics common to any type of bank account, such as account holder name, account number and current balance. Imagine, however, that our banking program needs to support a number of specific types of account. For example, the bank might offer its customers an interest bearing savings account. A savings account will have all the characteristics of our BankAccount class but would also need a way to store the prevailing interest rate. One option would be to create a brand new class from the ground up called SavingsAccount which duplicates everything we have in our BankAccount class, plus extra members needed for a savings account. Another, more efficient method is to derive a SavingsAccount class from the BankAccount class and then add in the extra functionality into this subclass.
Creating a Subclass in C#
Now that we have ascertained that we need to create a sub class of our BankAccount class we can take a look at the code necessary to achieve this. Subclasses are declared in the same way as any other class with the exception that the class name is followed by a colon (:) followed by the name of the class from which it is to inherit. With this in mind we can begin by creating our SavingsAccount class:
public class BankAccount { public string accountName; public int accountBalance; public int accountNumber; public BankAccount (string name, int number) { accountName = name; accountNumber = number; } public int getAccountNumber() { return accountNumber; } public void setAccountNumber(int newNumber) { accountNumber = newNumber; } } public class SavingsAccount : BankAccount { } { }
POLYMORPHISM
Polymorphism Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name. Polymorphism allows a method of a class to be called without regard to what specific implementation it provides.
Method overriding
Virtual and Override keywords allows you to implement Methods Overriding in Base and Derived Classes. Different implementations of a method with the same name and signature in the base and sub-classes is called as Polymorphism.
Sample code
is and as keyword
To check the run-time type of an object, you can use either is or as keyword. is compares the type of the object with the given type and returns true if it is cast-able otherwise, it returns false.
24
25
26
Operator overloading
All unary and binary operators have pre-defined implementations, that are automatically available in any expressions. In addition to this pre-defined implementations, user defined implementations can also be introduced in C#. The mechanism of giving a special meaning to a standard C# operator with respect to a user defined data type such as classes or structures is known as operator overloading. Remember that it is not possible to overload all operators in C#. The following table shows the operators and their overloadability in C#.
Operator overloading
Operators Overloadability +, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded. +, -, !, ~, ++, --, true, false All C# unary operators can be overloaded. ==, !=, <, >, <= , >= All relational operators can be overloaded, but only as pairs. &&, || They can't be overloaded () (Conversion operator) They can't be overloaded +=, -=, *=, /=, %= These compound assignment operators can be overloaded. But in C#, these operators are automatically overloaded when the respective binary operator is overloaded. =, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded
int SafeDivision(int x, int y) { try { return (x / y); } catch ( (System.DivideByZeroException dbz) { System.Console.WriteLine("Division by zero attempted!"); return 0; } }
30