Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Inheritance & Polymorphism

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

C#

Inheritance & Polymorphism


Inheritance
Inheritance allows defining a class based on another class. This
makes creating and maintaining an application easy.

The class whose properties are inherited by another class is


called the Base class. The class which inherits the properties
is called the Derived class.

For example, base class Animal


can be used to derive Cat and Dog
classes. The derived class
inherits all the features from
the base class, and can have its
own additional features.

Defining the Animal class:

class Animal {
public int Legs {get;set;}
public int Age {get;set;}
}

Now we can derive class Dog:


class Dog : Animal {
public Dog(){
Legs = 4;
}
public void Bark(){
Console.WriteLine(”Woof”);
}
}
This code outputs “Woof”.

Pay attention to the syntax, a colon is used before the name of


the base class.
All public members of Animal pass become public members of Dog.
That is why it is possible to access the Legs member in the Dog
constructor.

A base class can have multiple derived classes.

Inheritance of Methods
A derived class inherits all the members of the base class,
including its methods.

For example:
class Person {
public void Speak(){
Console.WriteLine(”Hi there”);
}
}
class Student : Person {
int number;
}
static void Main(string[] args){
Student s = new Student();
s.Speak();
In the example above a Student object was created and called the Speak method,
which was declared in the base class Person, was called.

C# does not support multiple inheritance, so inheriting from


multiple classes in not possible, unless interfaces are used to
implement multiple inheritance.

Protected modifier
The protected modifier differs from private modifier, by the
means that it can be accessed in a derived class as well as in
the base class.
For example:

class Person{
protected int Name {get;set;}}
class Student : Person {
public Student(string Name){
this.Name = Name;}
public void Speak(){
Console.WriteLine(”Name: {0}” Name);}}
static void Main(string[] args){
Student s = new Student(”David”);
s.Speak();}
As it is seen, it is possible to modify the Name property of the base class
from the derived class.

If we would try to access the Name property outside the class,


we would get an error:
static void Main(string[] args){
Student s = new Student(”David”);
s.Name = ”Bob”; // Error

Sealed modifier
A class can prevent other classes from inherting it, or any of
its members, by using the sealed modifier.

For example:

sealed class Animal { ... }


class Dog : Animal { ... } // Error

The code above will result in an error as the sealed class Animal can not be
inherited.

Inheritance of Constructors & Destructors


Constructors are called when objects of a class are created.
With inheritance, the base class constructor and destructor are
not inherited, this means that a constructor and destructor of
a derived class should be defined instead.

However the base class constructor and destructor are being


invoked when objects of the derived class are created or deleted.
Consider the following example:
class Animal {
public Animal(){
Console.WriteLine(”Animal created”);
}
~Animal(){
Console.WriteLine(”Animal deleted”);
}
}
class Dog : Animal {
public Dog() {
Console.WriteLine(”Dog created”);
}
~Dog(){
Console.WriteLine(”Dog deleted”);
}
}
Animal class with a constructor and destructor has been defined and a derived
class Dog with its own constructor and destructor.

static void Main(string[] args){


Dog dog = new Dog();
}
This code outputs the following: “Animal created”, “Dog created”, “Dog
deleted”, “Animal deleted”.

As it can be seen the base class constructor is called first,


and only then is the derived class constructor.

Polymorphism
The word polymorphism means “having many forms”.

Typically, polymorphism occurs when there is a hierarchy of


classes and they are related through inheritance from a common
base class.

Polymorphism means that a single method can have a number of


different implementations.
For example, there is a program that allows users to draw
different shapes. Each shape is different, but they are drawn
using the same method, which was overridden.

In this case polymorphism can be leveraged to invoke the


appropriate draw method of any derived class by overriding the
same method in the base class. Such methods must be declared
using the virtual keyword in the base class.

For example:

class Shape {
public virtual void Draw(){
Console.WriteLine(”Base draw”);
}
}
The virtual keyword allows methods to be overridden in derived classes.

Implementation: keyword: override

class Circle : Shape {


public override void Draw(){
// Any code...
Console.WriteLine(”Circle draw”);
}
}
class Rectangle : Shape {
public override void Draw(){
// Any code...
Console.WriteLine(”Rectangle draw”);
}
}

As we can see, the Draw() method has been defined in the base class, but has
been redefined in derived classes to serve the needs of that class. This is
possible, because the Draw() method has been declared as virtual.

The main function would look like this:


static void Main(string[] args){
Shape c = new Circle();
c.Draw();
Shape r = new Rectangle();
r.Draw();
}
The code outputs the following: “Circle draw”, “Rectangle draw”.
To summarize, polymorphism is a way to call the same method for different
objects and generate different results based on the object type. This
behavior is achieved through virtual methods in the base class.

Shape c = new Circle();


Shape is base class. Circle is the derived class.

So why use polymorphism ? It is possible to just instantiate


each object of its type and call its method, as in:
Circle c = new Circle();
c.Draw();
The output of this code would be the same as output of the code before, if
we would to call c.Draw() method in that example.

The polymorphic approach allows us to treat each object the same


way. As all objects are of type Shape, it is easier to maintain
and work with them. It is possible, for example, to have a list
(or array) of objects of that type and work with them
dynamically, without knowing the actual derived type of each
object.

Abstract
As described above, polymorphism is when there are different
derived classes with the same method, which has different
implementations in each class. This behavior is achieved through
virtual methods that are overridden in the derived classes.

In some situations there is no need for a virtual method to have


a separate definition in the base class.

These methods are thus defined using the abstract keyword, and
specify that the derived classes must define that method on
their own.

It is not possible to create objects of a class containing an


abstract method, which is why the class itself should be
abstract.

For example:

abstract class Shape


{
public abstract void Draw()
}
As it is seen, the Draw method is abstract and thus has no body.
Even the curly braces are unnecessary, there should be only the
semicolon, at the end of the statement.

Abstract method declarations are only permitted in abstract


classes

Abstract Classes
An abstract class is intended to be a base class of other
classes. It acts like a template for its derived classes.

Presence of an abstract class, allows derivation of other


classes.

For example:

abstract class Shape {


public abstract void Draw();
}
class Circle : Shape {
public override void Draw(){
Console.WriteLine(”Circle draw”);
}
}
class Rectangle : Shape {
public override void Draw(){
Console.WriteLine(”Rectangle draw”);
}
}
static void Main(string[] args){
Shape c = new Circle();
c.Draw();
}
This code is an equivalent to the previous example where the Draw method
was defined as virtual.

It is not possible to modify an abstract class with a sealed


modifier because the two modifiers have opposite meanings. The
sealed modifier prevents class from being inherited, while the
abstract modifier requires a class to be inherited.
Abstract classes have the following features:

-An abstract class can not be instantiated

-An abstract class may contain abstract methods and


accessors

-A non-abstract class derived from an abstract class must


include actual implementations of all inherited abstract
methods and accessors.

Interfaces
An interface is a completely abstract class, which contains
only abstract members.

It is declared using the interface keyword:

public interface IShape


{
void Draw();
}
The code above defines an abstract method Draw. Note the capital letter I
in the beginning, interface names usually start with the capital letter I.

All members of the interface are by default abstract, so no


need to use the abstract keyword.

Also, all members of an interface are always public and no


modifier can be applied to them.

Interfaces can contain properties, methods and etc, but can


not contain fields.

Interface Implementation
When a class implements an interface, it must also implement,
or define, all of its methods.

The term implementing an interface is used (opposed to the


term “Inheriting from”) to better describe the process of
creating a class based on an interface. An interface simply
describes what a class should do. The class implementing the
interface must define how to accomplish the behaviors.
The syntax to implement an interface is the same as that to
derive a class:

public interface IShape


{
void Draw();
}
class Circle : IShape {
public void Draw() {
Console.WriteLine(”Circle Draw”);
}
}
static void Main(string[] args) {
IShape c = new Circle();
c.Draw();
}

The override keyword is not needed when an interface is implemented.

A class can implement multiple interfaces, this is why it is


preferred instead of abstract classes, which can be inherited
only once.

Therefore, by using interfaces it is possible to include


behavior from multiple sources in a class.

To implement multiple interfaces, a comma is used to separate


the list of interfaces when creating the class.

For example:

public interface IShape


{
void Draw();
}
...
...
class SomeClass : IShape, IAnimal, IUnit, etc...
c.Draw();
}
Nested Classes
C# supports nested classes: a class that is a member of
another class.

For example:
class Car {
string name;
public Car(string name){
this.name = name;
Motor m = new Motor();
}
public class Motor {
// Some code
}
}
Here the Motor class is nested in the Car class and can be used similar to
other members of the class.

A nested class acts as a member of the class, so it can have


the same access modifiers as other members (public, private,
protected).

Namespaces
When a blank project is created, it has the following
structure:

using System;

namespace ProjectName
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(”Hello World!”);
}
}
}
The whole program is inside a namespace.
Namespaces declare a scope that contains a set of related
objects. It is possible to use a namespace to organize code
elements.

The using keyword states that the program is using a given


namespace.

For example, the System namespace is using System;


used by default in a program. namespace …

Without the using statement, it would be necessary to specify


the namespace wherever it is used:

System.Console.WriteLine(”Hello”);

The .NET Framework uses namespaces to organize its many


classes. System is one example of a .NET Framework namespace.

Declaring a namespace can help group classes and method names


in large projects

You might also like