Search My Warehouse

2009-11-25

Inheritance and Polymorphism

Inheritance:

Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class.

Conceptually, a derived class is a specialization of the base class. For example, if you have a base class Animal, you might have one derived class that is named Mammal and another derived class that is named Reptile. A Mammal is an Animal, and a Reptile is an Animal, but each derived class represents different specializations of the base class.

  • When you define a class to derive from another class, the derived class implicitly gains all the members of the base class, except for its constructors and destructors.
  • The derived class can thereby reuse the code in the base class without having to re-implement it.
  • In the derived class, you can add more members. In this manner, the derived class extends the functionality of the base class.

C# supports two types of Inheritance mechanisms:

1) Implementation Inheritance
2) Interface Inheritance

Implementation Inheritance:

- When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance

Interface Inheritance:

- When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance

In general Classes can be derived from another class, hence support Implementation inheritance At the same time Classes can also be derived from one or more interfaces Hence they support Interface inheritance Structs can derive from one more interface, hence support Interface Inheritance Structs cannot be derivedfrom another class they are always derived from SystemValueType

Multiple Inheritance:

C# does not support multiple implementation inheritance A class cannot be derived from more than one class However, a class can be derived from Multiple Interfaces.

------------------------------------

Inheritance Syntax:

Class derivedClass:baseClass
{
}


Interface Inheritance:

private Class derivedClass:baseClass , InterfaceX , InterfaceY
{
}

Abstract And Virtual Method:

When a base class declares a method as virtual, a derived class can override the method with its own implementation.

class baseClass
{
public virtual int fnCount()
{
return 10;
}
}

class derivedClass :baseClass
{
public override int fnCount()
{
return 100;
}
}

If a base class declares a member as abstract, that method must be overridden in any non-abstract class that directly inherits from that class.

If a derived class is itself abstract, then it inherit abstract members without implementing them.

Abstract and virtual members are the basis for polymorphism, which is the second primary characteristic of object-oriented programming.


Polymorphism:

Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance.

  • At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.
  • Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.
Virtual methods enable you to work with groups of related objects in a uniform way.

For example, suppose you have a drawing application that enables a user to create various kinds of shapes on a drawing surface. You do not know at compile time which specific types of shapes the user will create. However, the application has to keep track of all the various types of shapes that are created, and it has to update them in response to user mouse actions. You can use polymorphism to solve this problem in two basic steps:

  • Create a class hierarchy in which each specific shape class derives from a common base class.
  • Use a virtual method to invoke the appropriate method on any derived class through a single call to the base class method.
Example:

public class Shape
{
// A few example members
public int X { get; private set; }
public int Y { get; private set; }
public int Height { get; set; }
public int Width { get; set; }

// Virtual method
public virtual void Draw()
{
Console.WriteLine("Performing base class drawing tasks");
}
}

class Circle : Shape
{
public override void Draw()
{
// Code to draw a circle...
Console.WriteLine("Drawing a circle");
base.Draw();
}
}
class Rectangle : Shape
{
public override void Draw()
{
// Code to draw a rectangle...
Console.WriteLine("Drawing a rectangle");
base.Draw();
}
}
class Triangle : Shape
{
public override void Draw()
{
// Code to draw a triangle...
Console.WriteLine("Drawing a triangle");
base.Draw();
}
}

class Program
{
static void Main(string[] args)
{
// Polymorphism at work #1: a Rectangle, Triangle and Circle
// can all be used whereever a Shape is expected. No cast is
// required because an implicit conversion exists from a derived
// class to its base class.
System.Collections.Generic.List shapes = new System.Collections.Generic.List();
shapes.Add(new Rectangle());
shapes.Add(new Triangle());
shapes.Add(new Circle());

// Polymorphism at work #2: the virtual method Draw is
// invoked on each of the derived classes, not the base class.
foreach (Shape s in shapes)
{
s.Draw();
}

// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}

}
-----------------------------------------

/* Output:
Drawing a rectangle
Performing base class drawing tasks
Drawing a triangle
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks
*/

------------------------------------------



Source: MSDN & Exforsys

Class And Objects

Introduction:

In our world we have classes and objects for those classes. Everything in our world is considered to be an object. For example, people are objects, animals are objects too, minerals are objects; everything in the world is an object. Easy, right? But what about classes?

In our world we have to differentiate between objects that we are living with. So we must understand that there are classifications (this is how they get the name and the concepts of the Class) for all of those objects. For example, I'm an object, David is object too, Maria is another object. So we are from a people class (or type). I have a dog called Ricky so it's an object. My friend's dog, Doby, is also an object so they are from a Dogs class (or type).

A C# Class is considered to be the primary building block of the language.

We use classes as a template to put the properties and functionalities or behaviors in one building block for a group of objects and after that we use the template to create the objects we need.

The class: A building block that contains the properties and functionalities that describe some group of objects. We can create a class Person that contains:

1. The properties of any normal person on the earth like: hair color, age, height, weight, eye color.
2. The functionalities or behaviors of any normal person on the earth like: drink water, eat, go to the work.

There are 2 kinds of classes: The built-it classes that come with the .NET Framework, called Framework Class Library, and the programmer defined-classes which we create ourselves.

The class contains data (in the form of variables and properties) and behaviors (in the form of methods to process these data).

The object: It's an object of some classification (or class, or type) and when you create the object you can specify the properties of that object. What I mean here is: I, as an object, can have different properties (hair color, age, height, weight) than you as another object. For example, I have brown eyes and you have green eyes. When I create 2 objects I will specify a brown color for my object's eye color property and I will specify a green color for your object's eye color property.



class Person
{
public int Age;
public string HairColor;
}


This is our simple class which contains 2 variables.

static void Main(string[] args)
{
Person Michael = new Person();
Person Mary = new Person();

// Specify some values for the instance variables
Michael.Age = 20;
Michael.HairColor = "Brown";
Mary.Age = 25;
Mary.HairColor = "Black";
// print the console's screen some of the variable's values
Console.WriteLine("Michael's age = {0}, and Mary's age = {1}",Michael.Age,
Mary.Age);
Console.ReadLine();
}



So we begin our Main method by creating 2 objects of type Person. After creating the 2 objects we initialize the instance variables for object Michael and then for object Mary. Finally we print some values to the console. Here, when you create the Michael object, the C# compiler allocates a memory location for the 2 instance variables to put the values there. Also, the same thing with the Mary object; the compiler will create 2 variables in memory for Mary object. So each object now contains different data.


Using Properties in Functions:

class Person
{
private int age;
private string hairColor;
public int Age
{
get
{
return age;
}
set
{
if(value <= 65 && value >= 18)
{
age = value;
}
else
age = 18;
}
}
public string HairColor
{
get
{
return hairColor;
}
set
{
hairColor = value;
}
}
}


I made some modifications, but focus on the new 2 properties that I created. So the property consists of 2 accessors. The get accessor, responsible of retrieving the variable value, and the set accessor, responsible of modifying the variable's value. So the get accessor code is very simple. We just use the keyword return with the variable name to return its value. So the following code:

get
{
return hairColor;
}


returns the value stored in hairColor.


static void Main(string[] args)
{
Person Michael = new Person();
Person Mary = new Person();

// Specify some values for the instance variables
Michael.Age = 20;
Michael.HairColor = "Brown";
Mary.Age = 25;
Mary.HairColor = "Black";

// print the console's screen some of the variable's values
Console.WriteLine("Michael's age = {0}, and Mary's age = {1}",Michael.Age,
Mary.Age);
Console.ReadLine();
}


Here I created the same objects from the last example, except that I used only properties to access the variable instead of accessing it directly. Look at the following line of code

Michael.Age = 20;

When you assign a value to the property like that C# will use the set accessor. The great thing with the set accessor is that we can control the assigned value and test it; and maybe change to in some cases. When you assign a value to a property C# changes the value in a variable and you can access the variable's value using the reserved keyword value exactly as I did in the example. Let's see it again here.

set
{
if(value <= 65 && value >= 18)
{
age = value;
}
else
age = 18;
}

Here in the code I used if statement to test the assigned value because for some reason I want any object of type Person to be aged between 18 and 65. Here I test the value and if it is in the range then I will simply store it in the variable age. If it's not in the range I will put 18 as a value to age.

We create a class by defining it using the keyword class followed by the class name:

class Person

Then we open a left brace "{" and write our methods and properties. We then close it with a right brace "}". That's how we create a class. Let's see how we create an instance of that class.

In the same way as we declare a variable of type int we create an object variable of Person type with some modifications:

int age;
Person Michael = new Person();


In the first line of code we specified integer variable called age. In the second line we first specified the type of Object we need to create, followed by the object's name, followed by a reserved operator called new. We end by typing the class name again followed by parentheses "()".

Let's understand it step-by-step. Specifying the class name at the beginning tells the C# Compiler to allocate a memory location for that type (the C# compiler knows all the variables and properties and methods of the class so it will allocate the right amount of memory). Then we followed the class name by our object variable name that we want it to go by. The rest of the code "= new Person();" calls the object's constructor. We will talk about constructors later but for now understand that the constructor is a way to initialize your object's variable while you are. For example, the Michael object we created in the last section can be written as following :

Person Michael = new Person(20, "Brown");

Here I specified the variable's values in the parameter list so I initialized the variables while creating the object.


Source: DevArticles

Feed