Encapsulation and Polymorphism - C# FOR BEGINNERS CRASH COURSE (2014)

C# FOR BEGINNERS CRASH COURSE (2014)

Chapter 11 Encapsulation and Polymorphism

11.1 Introduction to encapsulation

Encapsulation is the process of enclosing data and function within a physical or logical package. It helps the developers to prevent the access to the essential details of an application. It binds the code and data together.

Abstraction states that all the information is present, but only relevant information is provided to the user.

Abstraction and encapsulation are related features. Encapsulation assists abstraction by providing means of hiding the non-essential details. Using encapsulation some information is visible and others are hidden.

11.2 Access specifier in C#

An access specifier defines the scope of a class member. The member is used for referring the functions and variables of a class. A program consists of one or more classes. Some member of the class needs to be accessed by other classes.

Types of Access Specifier

The following access specifiers are supported by C#.

· public

· private

· protected

· internal

· protected internal

Public Access Specifier

Public access specifier allows the class to expose the member variables and functions with other classes. The member declared as public can be accessed from outside the class.

Example of public access specifier

Example 38:

using System;

namespace public1

{

class User

{

//member variables

public string name;

public int age;

public void AddValue()

{

Console.WriteLine("Enter the user name:");

name = Console.ReadLine();

Console.WriteLine("Enter the age:");

age = Convert.ToInt32(Console.ReadLine());

}

public void Show()

{

Console.WriteLine("User name is:{0}",name);

Console.WriteLine("Age is:{0}",age);

}

}

class Program

{

static void Main(string[] args)

{

User u = new User();

u.AddValue();

u.Show();

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Enter the user name:

Mark

Enter the age:

20

User name is: Mark

Age is: 20

Private Access Specifier

The private access specifier allows the user to hide classes’ member variables and functions from other class objects and functions. The private members are not visible from outside the class. Only the class functions based within the class itself can access the private entity. Objects or instances of the class cannot access any private variables or functions as they are declared as external to the class.

Example:

Example 39:

using System;

namespace private1

{

class Student

{

//member variables

private string name;

private int age;

public void AddValue()

{

Console.WriteLine("Enter the student name:");

name = Console.ReadLine();

Console.WriteLine("Enter the age:");

age = Convert.ToInt32(Console.ReadLine());

}

public void Show()

{

Console.WriteLine("Student name is:{0}",name);

Console.WriteLine("Age is:{0}",age);

}

}

class Program

{

static void Main(string[] args)

{

Student s = new Student();

s.AddValue();

s.Show();

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Enter the student name:

Harry

Enter the age:

15

Student name is: Harry

Enter the age: 15

Protected access specifier

Protected access specifier allows the class to hide the member variables and functions from other class objects and functions, except from child classes. The specifier is useful during the implementation of inheritance.

Example:

Example 40:

using System;

namespace protected1

{

class Employee

{

//member variables

protected string name;

public void AddValue()

{

Console.WriteLine("Enter the employee name:");

name = Console.ReadLine();

}

public void Show()

{

Console.WriteLine("Employee name is:{0}",name);

}

}

class Program

{

static void Main(string[] args)

{

Employee e = new Employee();

e.AddValue();

e.Show();

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Enter the employee name:

Ajay

Employee name is: Ajay

Internal access specifier

Internal access specifier allows a class to expose its member functions and variables to the containing child classes or classes within the same application.

Example:

Example 41:

using System;

namespace internal1

{

class Location

{

//member variables

internal string city;

public void AddValue()

{

Console.WriteLine("Enter the city name:");

name = Console.ReadLine();

}

public void Show()

{

Console.WriteLine("City name is:{0}",name);

}

}

class Program

{

static void Main(string[] args)

{

Location l = new Location();

l.AddValue();

l.Show();

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Enter the city name:

London

City name is: London

Protected Internal access specifier

The protected internal access specifier allows a class to expose the member functions and variables to the containing class, child class, or classes in same application. The access to the derived classes outside the application is allowed.

Example:

Example 42:

using System;

namespace protectedinternal1

{

class number

{

//member variables

protected internal int no;

public void AddValue()

{

Console.WriteLine("Enter the number:");

no = Convert.ToInt32(Console.ReadLine());

}

public void Show()

{

Console.WriteLine("Number is:{0}",no);

}

}

class Program

{

static void Main(string[] args)

{

number n = new number();

n.AddValue();

n.Show();

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Enter the number:

10

Number is: 10

11.3 Polymorphism

Polymorphism is the ability of the function to exist in different forms. The word ‘poly’ means many and ‘morphos’ means forms.

There are two types of polymorphism:

· Static: The response to a function is decided at compile time

· Dynamic: The response to function is decided at run time

11.4 Static Polymorphism

The static polymorphism refers to entity which exists in different forms. C# has two approaches for implementing polymorphism.

· Function overloading

· Operator overloading

Function overloading

Function overloading helps a user to use the similar name for two or more functions. The function definition must be different from each other by type or number of arguments in the list.

Example:

Example 43:

using system;

namespace calculate

{

class calculate

{

public int Min(int no1, int no2)

{

if(no1 < no2)

{

return no1;

}

else

{

return no2;

}

}

public float Min(int no1, int no2)

{

if(no1 < no2)

{

return no1;

}

else

{

return no2;

}

}

class Program

{

static void Main(string[] args)

{

Program p = new Program();

Console.WriteLine("Minimum value is:{0}",p.Min(3,4));

Console.WriteLine("Minimum value is:{0}", p.Min(3.2F,1.2F));

Console.ReadLine();

}

}

}

}

When the code is compiled and executed, the output is:

Minimum value is: 3

Minimum value is: 1.2

11.5 Dynamic Polymorphism

C# has two approaches for implementing dynamic polymorphism. They are:

· Abstract classes: They are unique type of base classes containing abstract class members. The class members derived from the abstract class must implement abstract functions and properties.

· Virtual functions: They do not really exist. They appear to be present in some parts.

Abstract class

An abstract class provides partial implementation of the class. When the derived class inherits it, the implementation is completed. There are abstract methods which are implemented using derived class.

Rules for abstract class creation

· User cannot declare an abstract method outside the abstract class

· The instance of the abstract class cannot be created

· A class derived from an abstract class must override all the methods of the class

· The abstract class cannot be declared as sealed

Example:

Example 44:

using System

namespace poly

{

abstract class Result

{

public abstract int average();

}

class Data: Result

{

private int sub1;

private int sub2;

public Data(int x, int y)

{

sub1 = x;

sub2 = y;

}

public override int average()

{

Console.WriteLine("The average is:");

return (x + y / 2);

}

}

class Program

{

static void Main(string[] args)

{

Data d = new Data(30, 70);

int a = d.average();

Console.WriteLine("Average:{0}",a);

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

The average is:

Average: 50

Virtual Functions

If you need a function that is defined in a class and needs to be implemented by an inherited class, the virtual function is used. The inherited class modifies the functionality of the inherited class depending on the requirement. The call to method is at runtime.

The virtual keyword is used before the return type of the function.

Example:

Example 45:

using System;

namespace virtual1

{

class Calculate

{

protected int x, y;

public Calculate(int l = 0, int m = 0)

{

x = l;

y = m;

}

public virtual int operation

{

return 0;

}

}

class Multiplication : Calculate

{

public Multiplication (int l = 0, int m = 0):base(l,m)

{

}

public override int operation()

{

Console.WriteLine("Multiplication is:");

return x * y;

}

}

class Addition : Calculate

{

public Addition (int l = 0, int m = 0):base(l,m)

{

}

public override int operation()

{

Console.WriteLine("Addition is:");

return x + y;

}

}

class call

{

public void callvalue(Calculate c)

{

int z;

z = c.operation();

Console.WriteLine("Result:{0}",z);

}

}

class Program

{

static void Main(string[] args)

{

call p = new call();

Multiplication m = new Multiplication(10,2);

Addition t = new Addition(15,16);

p.callvalue(m);

p.callvalue(t);

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Multiplication is:

Result: 20

Addition is:

Result: 31