Académique Documents
Professionnel Documents
Culture Documents
OOP with C#
Objectives
Accessor (get) and Mutator (set) Named Property Sealed classes Abstract Class and Method
2
Inheritance
Polymorphism
C# Classes
A Class is a custom User Defined Type (UDT) A Class consists of data (attributes) and functions (methods) Example: To model a generic Employee, we can define an Employee Class
Employee Class
Employee attributes:
string fullname; int empID; float currPay;
methods:
void GiveBonus(float amount); void DisplayStats();
4
Source Code
using System; namespace Employee { public class Employee { // private data private string fullName; private int empID; private float currPay; // Default ctor. public Employee(){ } // Custom ctor public Employee(string fullName, int empID, float currPay) { // Assign internal state data. Note use of 'this' keyword this.fullName = fullName; this.empID = empID; this.currPay = currPay; }
Overloading of Methods is same as C++. Constructors can be overloaded. For method resolution, return type alone is not necessary! Is the keyword 'this' always necessary? Yes, if the parameter name and the class member name are same. Otherwise No! Static member functions can't use 'this' keyword. Why? The keyword 'this' can also be used to force one constructor to call another during the object creation Ex: public Employee(string fullName) : this(fullName, GetEmpId(), currPay) { }
7
Encapsulation
Hiding unnecessary implementation details "is-a" and "has-a" relationship "is-a" means sub-classes or derived classes "has-a" means containment or delegation It is the ability of the language to treat related objects the same way When sub-classes override the behavior defined by base a class, they are essentially redefining how they respond to the same message
9
Inheritance
Polymorphism
Examples
Encapsulation
DBReader f = new DBReader(); // details are hidden is-a Relationship f.Open("@C:\foo.mdf"); // process the database file Object f.Close();
Inheritance Polymorphism
Shape void Draw( ) Hexagon Circle
Shape Hexagon
has-a Relationship
Draw()
Draw()
Car Radio
10
The main objective of encapsulation is: the object's instance should be allowed to access the internal member data directly. It also provides the integrity of state data. How to do this? Using private, public, protected, and protected internal keywords To manipulate the private data, C# provides two methods:
Accessor
class Employee {
private string fullName; public string GetName() { return fullName; } ..
Mutator
class Employee {
private string fullName; public string SetName(string n) { fullName = n; } .
12
Class Properties
You can define a named property to avoid using two different get and set methods The property is a single named field which wraps the private data. These property names can then be used in Main( ). Ex: Assume EmpID is the name of the property
public static void Main() { Employee e = new Employee(); e.EmpID = 121; // set Console.WriteLine(e.EmpID); // get }
13
The named property A in the previous slide was able to read and write. How to restrict the access of A as R/W? For Read-Only: simply define a property without a set block For write-only: simply define a property without a get block Ex: public float Pay public float Pay
{
get { return currPay; }
} }
15
{
set { currPay = value; }
The static keyword can be used for properties also The only difference is that, now these properties are bound to a class and not to an instance Ex: Employee.EmpID = 111; Can a constructor be declared as static? Yes, but it is strange! Why? Because, constructors are executed during object creation Static constructors are used to initialize static data
16
17
Read-Only Fields
Read-Only properties provide data preservation: keyword to be used is: "readonly" Ex: public readonly int rofield; You can't assign any value to the readonly fields, except in a constructor Ex: void SomeMethod() { rofield = 123; } // Error Static readonly fields can also be used. It is useful to associate many constant values bound to a class. It may be look similar to 'const' declaration. The difference, however, is that const is resolved at compiletime and static readonly is resolved at run-time. The other context in which it is valid to pass a readonly field as an out or ref parameter.
19
Inheritance facilitates code reuse Inheritance provides dependency between types Inheritance comes in two flavors:
Visibility Control
Keyword
public
23
All members of the base class except constructor & destructors are inherited Inheritance member may not be accessible in a derived class because of its declared accessibility
Consider
class A { private int x; protected int y; public int z; } class B:A { public void setxyz() { x=10; // error x is private y=20; z=30; // ok } }
cant access protected data from object instance Eg: A a=new A(); a.y=5; //error a.z=20; //ok
24
Accessibility constraints
1. 2.
3.
Constraints are Direct base class of a derived class must be at least as accessible as the derived class itself Accessibility domain of a member is never larger than that of the class containing it Return type of method must be at least as accessible as the methods itself
Eg for 1.a. class A {.} public class B:A { } // is illegal A is internal by default Eg 1.b. class A {. private class B { public int x; } } // public data x is not accessible outside the class B. because B is private the x reduced to private
Eg for 2&3. class A {. } public class B { A method1() { } Internal A method2() { } Public A method3() // Error } All methods in B specify A as their return types method3 is error because an accessibility level higher than that of its return type
25
When a derived class object is created an appropriate constructor for derived class is created A subclass constructor automatically calls the base class constructor, by default For that derived class uses the base keyword
26
Example
using System Class Room { public int length, breadth; public Room(int x, int y) { length = x; breadth=y; } public int Area() { return (length * breadth); } } Class Lroom:Room { int height; public Lroom(int x, int y, intz) : base(x,y) { height = z; } public int volume() { return(length * breadth * height); } }
27
Contd..
Class InherTest { public static void Main() { Lroom r1=new Lroom(14,12,10); int area1 = r1.Area() int volume1=r1.volume(); Console.WriteLine(Area = +area1); Console.WriteLine(Volume = +volume1); } }
28
Multilevel inheritance
The chain ABC is known as inheritance path. The constructor are created from the top downwards
A B C
29
Multiple Inheritance
In C#, a given class can have exactly one direct base class It is not permitted to have a single type with one or more base classes
You know that a private member can't be accessed by even subclasses "protected " data or methods can be accessed by subclasses
If you want to design a class that can't be inherited, then use the keyword: "sealed " A sealed class cannot also be an abstract class. It also enables certain run-time optimizations
30
Sealed Classes
PTSalesPerson
Manager
Add a subclass PTSalesPerson for SalesPerson class to have part time sales people. Since we can't think of more child classes under PTSalesPerson, we shall seal it Sealed classes are most useful for designing standalone classes. Ex: String class in the System namespace Example
public sealed PTSalesPerson : SalesPerson { . }
31
32
Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name. For Example, assume that you have added a new method to Employee class as: public void GiveBonus(float amount) { currPay += amount; } This method is common for all objects derived from Employee. However, our objective is to design this to behave differently for Manager and SalesPerson. This means that the subclasses should be able to provide different interfaces to Employee class Polymorphism is achieved through " virtual " and " override " keywords
33
Types of Polymorphism
Interface polymorphism - Multiple classes may implement the same interface, and a single class may implement one or more interfaces. Interfaces are essentially definitions of how a class needs to respond. An interface describes the methods, properties, and events that a class needs to implement. Inheritance polymorphism - Multiple classes may inherit from a single base class. By inheriting, a class receives all of the methods, properties, and events of the base class in the same implementation as the base class. Polymorphism through abstract classes - Abstract classes provide elements of both inheritance and interfaces. An abstract class is a class that cannot be instantiated itself; it must be inherited.
34
Example
public class Employee { public virtual void GiveBonus(float amount) { currPay += amount; } } public class SalesPerson : Employee { public override void GiveBonus(float amount) { int salesBonus = 0; if (numberOfSales > 200) salesBonus = 1000; base.GiveBonus(amount + salesBonus); } }
Base Claass
You can reuse the base class method by using the keyword base
35
Abstract Classes
An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on an abstract class An abstract class is permitted (but not required) to contain abstract members An abstract class cannot be sealed. Ex: If the Employee class is declared as abstract, the the following stmt. gives an error: Employee e = new Employee();
36
Contd..
Characteristics it cannot be instantiated directly It can have abstract members Cannot apply a sealed modifier to it
37
Abstract Methods
When an instance method declaration includes the modifier abstract, it is called abstract method It is implicitly virtual method & does not provide implementation Ex: public abstract void Draw(int x, int y); It ends with semicolon
38
Contd..
Characteristics it cannot have implementation Its implementation must be provided in non-abstract derived classes by overriding the method It can only be declared in abstract classes It cannot take static or virtual modifier
39
Method Hiding
The base class method with virtual & the subclass method with the keyword override, resulted in hiding the base class method from subclass How to override a method without declaring it virtual? Solution is use of new modifier Modifier new tell the compiler that the derived class method hides the base class method
40
Example
Using system; Class Base { public void Display( ) { CW(Base method);} } Class Derived:Base { public new void Display( ) { CW (Derived Method);} } Class Test { public static void Main() { Derived d= new Derived(); d.Display(); } }
41
Method Hiding
Method hiding is opposite of Method overriding Assume that Oval is-a type of Circle. Of course you can define a method Draw() which overrides Draw() of its parent class and provide its own versioning. However, if we want to prevent the Oval class from inheriting any previous logic, use "new" keyword
public class Oval : Circle { public Oval(){base.PetName = "Joe";} // Hide base class impl if they create an Oval. new public void Draw() { Console.WriteLine("Oval with class versioning"); } }
new keyword breaks the relationship between base class of abstract Draw() and the derived class version
42
new Modifier
// The new modifier using System; public class MyBaseC { public static int x = 55; public static int y = 22; }
Output: 100 55 22
public class MyDerivedC : MyBaseC { new public static int x = 100; // Name hiding public static void Main( ) { Console.WriteLine(x); // Display the overlapping value of x: Console.WriteLine(MyBaseC.x); // Access the hidden value of x: Console.WriteLine(y); // Display the unhidden member y: } }
43
The subclass Circle does not override Draw(), whereas Hexagon does Refer to Shapes Project
44
End of Chapter 4
45