0% found this document useful (0 votes)
90 views

Module-2 With Content

The document discusses object-oriented programming concepts in C# .NET, including classes, objects, inheritance, encapsulation, and polymorphism. It covers creating and using classes and objects, class members like methods and properties, access modifiers, nested classes, partial classes, and arrays of objects. The key chapters discussed are on classes and objects, encapsulation, and polymorphism. Concepts like inheritance, abstraction, interfaces, and polymorphism via method overloading and overriding are explained.

Uploaded by

Pronab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

Module-2 With Content

The document discusses object-oriented programming concepts in C# .NET, including classes, objects, inheritance, encapsulation, and polymorphism. It covers creating and using classes and objects, class members like methods and properties, access modifiers, nested classes, partial classes, and arrays of objects. The key chapters discussed are on classes and objects, encapsulation, and polymorphism. Concepts like inheritance, abstraction, interfaces, and polymorphism via method overloading and overriding are explained.

Uploaded by

Pronab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Programming using C# .

NET [18MCA51, 16/17MCA52]


Module – 2: Classes, Objects and Object-Oriented Programming
Chapter – 1: Classes and Objects
1.1 Classes and Objects
1.2 Creating a Class
1.3 Creating an Object
1.4 Using this Keyword
1.5 Creating an Array of Objects
1.6 Using the Nested Classes
1.7 Defining Partial Classes and Method
1.8 Returning a Value from a Method
1.9 Describing Access Modifiers
1.10 Static Classes and Static Members
1.11 Properties
1.12 Read-only Property, Static Property
1.13 Indexers
1.14 Structs: Syntax of a struct and Access Modifiers for structs
1.15 System.Object class
Chapter - 2: Encapsulation
2.1 Encapsulation
2.2 Encapsulation using accessors and mutators
2.3 Encapsulation using Properties
2.4 System Data Types
2.5 Inheritance and Constructors
2.6 Sealed Classes and Sealed Methods
2.7 Extension methods
Chapter - 3: Polymorphism
3.1 Compile time Polymorphism/ Overloading
3.2 Runtime Polymorphism/Overriding
3.3 Abstraction
3.4 Abstract classes
3.5 Abstract methods
3.6 Interfaces: Syntax of Interfaces
3.7 Implementation of Interfaces and Inheritance

Prepared by
Mrs. Suma M G
Assistant Professor
Department of MCA
RNSIT
Bengaluru – 98.
Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP

Chapter - 1

Class, Objects and Object Oriented Programming


1.1 Classes and Objects:
Classes allows you to control all the functions that can be applied to a given set of data as well as how to access
the data.
Classes also give the ability to extend a runtime environment and allow the developer to reuse the existing
functionalities of the runtime environment. Then use that class to create the objects as needed.
In this section, you learn to perform the following tasks:
• Creating a class • Using Nested Classes
• Creating an object • Using methods as Class Members
• Using this Keyword • Passing an object as an argument to a method
• Creating an Array of Objects • Returning a value from a method
• Defining partial classes and methods • Describing access modifiers

1.2 Creating a Class:


A class declaration in C# is composed of attributes, modifiers, the class name, base class and interfaces, and a
body. Attributes, modifiers, and bases are all optional.
Syntax:
The body of the class class <Class_name> {
contains class members that <access_modifier> [static] variable_type fields, constants
can include constants, fields <access_modifier> [static] return_type methodName(args..){ - - - - }
(or variables), methods, ... constructors, destructors ...
properties, indexers, events, ... properties ...// for component-based programming
operators, and nested types. ... events ...
Nested types are defined by ... indexers ... // for convenience
class, interface, delegate, ... overloaded operators ...
struct, or enum declarations ... nested types (classes, interfaces, structs, enums, delegates)
within the class body. }

1.3 Creating an Object:


In C#, objects help you to access the members of a class – fields, methods and properties by using the dot (⚫)
operator.
• An object is a given instance of a particular class in memory.
 In C#, the new keyword is the way to create an object.

Syntax:
<ClassName> <ObjectName> = new <ClassName>();

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 1 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
1.4 Using this Keyword:
The “this” keyword refers to the current instance of a class. With the “this” keyword, you can access an instance
of a class and use it with instance methods, instance constructors, and instance properties.
Syntax: Note:
• To access the instance members of a class, use dot(⚫) operator
this.members;
• Cannot be used with static members because static members are
accessed by a class and not by the instance of the class.
Example 1.1:
class Student{
string name, sid;
int marks;
public Student(string name, string sid, int marks){
this.name = name;
this.sid = sid;
this.marks = marks;
}
//If the user calls this ctor, forward to the 3-arg version.
//public Student() : this("Kalpana","MCA01",95) { }
public Student() {
name = "Kalpana";
sid = "MCA01";
marks = 95;
}
public void displayData(){
Console.WriteLine("Name:{0}\nID:{1}\nMarks:{2}",name,sid,marks);
}
}
class thisdemo {
static void Main(string[] args){
Student st1 = new Student();
Console.WriteLine("Student Details:");
st1.displayData();
Student st2 = new Student("Tanuja", "MCA02", 85);
st2.displayData();
Console.ReadLine();
} } }

1.5 Creating an Array of Objects:


To create an array of objects in C#, follow the below steps:
➢ Create an array ➢ Then create the individual elements of the array.

Syntax: <ClassName>[] ObjectName = new <ClassName>[size];

Example: Employee[] manager = new Employee[size];


Note: you cannot create an array and its individual elements simultaneously.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 2 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
1.6 Using the Nested Classes:
A Nested class is a class that is defined inside another class. This class acts as the member of the parent class
in which it is defined.
Advantage: Accessing all the members of its outer class.
Example 1.2:
using System;
namespace Class_Demos {
class OuterClass {
int i;
public OuterClass() { i = 10; }
public void OutDisplay() {
Console.WriteLine("This is Outer Class");
}
public class InnerClass {
public void InDisplay(OuterClass o){
Console.WriteLine("This is Inner Class");
Console.WriteLine("i value is:" +o.i);
}
}
}
class NestedClEx{
public static void Main(){
//Creating instance to outer class
OuterClass ob1 = new OuterClass();
ob1.OutDisplay();
//Creating instance to inner class
OuterClass.InnerClass iob = new OuterClass.InnerClass();
iob.InDisplay(ob1);
Console.Read();
} } }

1.7 Defining Partial Classes and Method:


The partial class is a class that enables you to specify the
definition of a class, structure, or interface in two or more Program1.cs
source files. All the source files, each containing a section
of class definition, combine when the application is
Compile to
complete. You may need a partial class when developers one single
are working on large projects. class
A partial class distributes a class over multiple separate Program1.cs
files; allowing developers to work on the class
simultaneously. You can declare a class as partial by
using the “partial” keyword.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 3 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
All the divided sections of the partial class must be available to form the final class when you compile the
program. Let’s see that in above figure.
Syntax:
All the section must have the same accessibility public partial class student{
modifiers, such as public or private. public void avgmarks() { }
}
public partial class student{
public void avgmarks() { }
}

Partial method are only allowed in partial types, such as classes and structs. A partial method consists of 2
parts that listed below:
✓ Deals with defining the partial method Rules:
✓ Deals with implementing the partial method  Must have a void return type
 No access modifier are allowed for declaring a partial
declaration
method except for static
 Partial methods are private by default.
Example 1.3:

using System;
namespace Class_Demos{
partial class MyTest {
private int a;
private int b;
public void getAnswer(int a1, int b1){
a = a1;
b = b1;
}
static partial void Message();
}
partial class MyTest{
partial void Message(){
Console.WriteLine("Successfully accessed. . . . . . ");
}
public void DisplayAns(){
Console.WriteLine("Integer values: {0}, {1}", a, b);
Console.WriteLine("Addition:{0}", a + b);
Console.WriteLine("Multiply:{0}", a * b);
Message();
}
}
class PartialEx{
public static void Main(){
MyTest ts = new MyTest();
ts.getAnswer(2, 3);
ts.DisplayAns();
Console.Read();
}}}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 4 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
1.8 Returning a Value from a Method:
A method can return a value to the caller of the method.
➢ If the return type is void, then the method will not return any value.
➢ If the return type is other than void, such as int, double, string or class_type then the method can return
any type of value using return keyword.
Example 1.4:

using System;
namespace Class_Demos{
class MyArea {
double l, b, area;
public double RectArea() {
Console.WriteLine("Enter the Length");
l = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the Breadth");
b = double.Parse(Console.ReadLine());
area = l * b;
Console.WriteLine("The area of Rectangle:" + area);
return (area);
}
}
class ReturnValue{
static void Main(){
MyArea obj = new MyArea();
obj.RectArea();
Console.WriteLine("Press Enter to quit....");
Console.ReadLine();
} } }

1.9 Describing Access Modifiers:


Access modifiers help to avoid jumbling of data and methods with the existing code as well as protect an object
of a class from outside interference. These modifiers do this by defining a certain scope to access data and
methods in a restricted manner.
Table 1.1: List of the access modifiers

Modifiers Meaning
public Allows public access to members both inside and outside a class without any restrictions.

internal Allows internal access to members. Only the current assembly can access these members.
Allows protected access to members. You can access protected members from either the class in
protected
which they are declared or a class derived from the class in which they are declared.
Allows private access to members. Private members have the least access permission level; you
private
can either access then within the body of the class or in the structure in which they are declared.
protected Allows access to the members of the current assembly, the containing class, and the class derived
internal from the containing class.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 5 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
1.10 Static Classes and Static Members:
C# class (and structure) members may be defined using the static keyword.
 Static methods  Static data  Static classes

Conventions to use “static” keyword:


 can be used with classes, fields, methods, properties, operators, events, and constructors
 static methods and properties can only access static fields and static events.
 but cannot be used with indexers, destructors, or types other than classes.
 can't use “this” keyword.
Note:
✓ static method is also known as class method[belongs to class not an object]
✓ non-static method is known as instance method.

Static methods
A C# class can contain both static and non-static methods. When we declare a method with the help of the
keyword static, it becomes a static method.
For using static methods,
 Creation of instance is not necessary.
 A static method only access other static data and methods
 Static methods cannot access data members and members’ method directly – they must use an object
reference.
Example 1.5:
using System;
namespace Examples {
class Stmethod{
static int record=0;
int i;
Stmethod(){
record++;
i++;
}
static void printrecord(){
Console.WriteLine ("No of stud record: {0}", record);
Console.WriteLine ("i: {0}", i);
}
static void Main(){
Stmethod stm1 = new Stmethod();
Stmethod stm2 = new Stmethod();
printrecord();
Console.ReadLine();
}
}
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 6 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
The class Stmethod is defined with a static member data record of int type. The purpose of the static member
data is to keep track of the number of objects created of a class Stmethod. Within the constructor, we use static
data member record++; whenever an object is created. The static member function printrecord() is display the
value of record is 2.
Static method can access within class: printrecord()
Static method can access from other class: Stmethod.printrecord()

Static data members:


When we declare a static field inside a class, it can be initialized with a value or all un-initialized static fields
automatically get initialized to their default values when the class is loaded at first time.
Characteristics:
 It is visible only within the class, but its lifetime is the entire program.
 Only one copy of static data member will exists for the entire class and is shared by all the objects of
that class.
 No matter how many objects of a class are created.
 All static variables are initialized to zero when the first object of its class is created.
Example 1.6:
using System;
namespace Examples {
class Stdata {
static int record=0;
Stdata(){
record++;
}
void printrecord(){
Console.WriteLine ("No of stud record: {0}", record);
}
static void Main(){
Stdata std1=new Stdata();
Stdata std2=new Stdata();
std1.printrecord();
std2.printrecord ();
Console.ReadLine();
} } }

When you create Stdata objects( std1, std2), memory for the non-static data field is allocated for each instance.
On the other hand, Static data is allocated once and shared among all object instances of the same type. So the
output of the record is 2 in both the instance of the class.

Static class:
When a class has been defined as static, no need to create an object. A static class must contain only static
members, except for constants (if this is not the case, you receive compiler errors).
Main benefit: We do not need to make any instance of this class; all members can be accessible with its own
name.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 7 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
Example 1.7:

using System;
namespace Examples {
static class StClass {
static int record = 0;
static void printrecord(){
Console.WriteLine("No of stud record: {0}", record);
}
static void Main() {
record = 2;
printrecord();
Console.ReadLine();
}
}
}

In the above example, StClass class is static class so it includes only static members. We can access all the
member of the static class directly; no need of instance of the class. So that members record and printrecord()
is accessing directly.

1.11 Properties:
A property is a member that provides a flexible mechanism
Syntax:
to read, write or compute the value of a private field. You
can implement properties with the type-safe get and set
set { <mutator-body> }
methods. get { <accessor-body >}

Example: The important thing is the “value” keyword, sets the value of the some property
Set { field with the contents of value token.
usn=value;
}

Note: Keep in mind about property that don’t have to have both a getter and a setter, you must have one of the
two.
➢ A property defined with both a getter and a setter is called a read-write property.
➢ A property defined with only a getter or accessor is called a read-only property.
➢ A property defined with only a setter or mutator is called a write-only property.
Example 1.8:

using System; class GetSetDemo1 {


namespace Chapter4_Examples{ static void Main() {
class Student{ Student st1 = new Student();
string name, branch, usn; st1.Studusn ="1RX12MCA01";
public string Studusn { Console.WriteLine("USN:"
set{ usn = value; } +st1.Studusn);
get{return usn;} Console.ReadKey();
} } } }
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 8 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
In the above example, we see the usage of Encapsulation by using properties. The property is composed using
a get block(accessor) and set block(Mutator). The get block returns the value of the some property field. The
set block sets the value of the some property field with the contents of “value” token.
In the C# “value” keyword represents the right hand side of the assignment. The underlying data type of the
value token depends on which sort of data it represents so that “value” token is called as object.

1.12 Read-only Property, Static Property:


A read-only property is a property that has a get accessor but does not have a set mutator. This means that you
can retrieve the value of a variable using a read-only property but you cannot assign a value to the variable.
Example 1.9:
using System; class ReadOnly{
namespace Class_Demos{ static void Main(){
class Student{ Student st1 = new Student();
string studusn; Console.WriteLine("USN: " +
public Student(){ st1.Studusn);
studusn="1RX13MCA01"; Console.ReadKey();
} }
public string Studusn { }
get { }
return studusn;
}
}
}
In the above example, the property “Studusn” is having only get accessor but not set mutator. So we can call
Studusn as a “read-only property”.

C# also supports “static” properties. The static members are accessed at the class level, not from an instance
(object) of that class. Static properties are manipulated in the same manner as static methods, as seen here:

For example, assume that the Student type defines a point of static data to represent the name of the institution
studying these students. You may define a static property as follows:
Example 1.10:
using System; class GetSetStatic {
namespace Chapter4_Examples{ static void Main(){
class Student { Student.Institution = "RNSIT";
string name, branch, usn; Console.WriteLine("Institution
static string instName; Name: "+Student.Institution );
public static string Institution{ Console.ReadKey();
set { instName = value; } }
get { return instName; } }
} }
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 9 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
1.13 Indexers:
Indexers allow you to use a class as an array and enable an object to access the members of a class using an
index notation.

Syntax: <access-modifier> <Return_Type> this [argument_list] {


get { // return the value specified by index }
set { // set the value specified by index }
}

Where,
 The access modifier can be private, public, protected or internal
 Return type can be any valid C# data type, such as int, float, double, string….
 this keyword shows that the object is of the current class.
 argument list specifies the parameters of the indexer.
 Must have at least one parameter; otherwise the compiler gives and error.
 Allows you to have multiple parameters and each parameter can be a different type, separated
by commas.
 Parameter types can be int, enum, or string.
 All indexers in the same class should have different signatures.
 The get and set portions accessors is the same as that of the indexer to which they belong.
Example 1.11:
using System;
namespace Class_Demos{
class Student {
string[] usn = new string[3];
public string this[int index]{
set { usn[index] = value; }
get {
if (index < 0 || index >= usn.Length)
return null;
else
return (usn[index]);
}
} }
class IndexerDemo {
public static void Main(){
Student slist = new Student();
slist[0] = "1RN12MCA01";
slist[1] = "1RN12MCA02";
slist[2] = "1RN12MCA03";
for (int i = 0; i < 3; i++)
Console.WriteLine(slist[i]);
Console.ReadKey();
}
} }

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 10 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
Indexers have the following additional features:
 Inheritance – Allows inheritance, which means a derived class can inherit a base class indexer.
However, modifiers such as virtual and override are used at the property level, not at the accessor level.
 Polymorphism – Allows polymorphism, which means the derived class can override a base class
indexer.
 Uniqueness – Provides a signature that uniquely identifies an indexer.
 Non – Static – Indexer cannot be static. If you declare, the compiler generates an error.
Example 1.12:

using System;
namespace Class_Demos{
class Student{
string name,usn,branch;
public Student(string n,string u,string b) {
name = n;
usn = u;
branch= b;
}
public Student(){}
//Define a string indexer
public string this[string index] {
get{
if (index == "name")
return name;
if (index == "usn")
return usn;
if (index == "branch")
return branch;
return "Unknown";
}
set {
if(index=="name")
name = value;
if (index == "usn")
usn = value;
if (index == "branch")
branch = value;
}
}
}
class IndexerDemo1 {
static void Main(){
Student std1 = new Student("Abhilash","1RN17MCA01","MCA");
Console.WriteLine("Name: " + std1["name"]);
Console.WriteLine("USN: " + std1["usn"]);
Console.WriteLine("Branch: " + std1["branch"]);

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 11 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP

Continued . . .

Student std2 = new Student();


std2["name"] = "Aditya";
std2["usn"] = "1RN17MCA02";
std2["branch"] = "MCA";
Console.WriteLine("*****Student details*****");
Console.WriteLine("Name: " + std2["name"]);
Console.WriteLine("USN: " + std2["usn"]);
Console.WriteLine("Branch: " + std2["branch"]);
Console.ReadLine();
} } }

Difference between Properties and Indexers:


Table 3.4: List of differences between property and indexers
Property Indexer
Allows identification by its name Allows identification by its signature
Allows elements of an internal collection or an object
Allows methods to be called as if they were
to be accessed by using an array notation on the object
public data members
itself.
Allows access through a simple name Allows access through an index
Uses static or an instance member Uses an instance member only
Provides no parameters to the get accessor of
Provides the same formal parameter list as the indexer
a property
Contains the same formal parameter list as the indexer,
Contains the implicit value parameter
in addition to the value parameter.

1.14 Structs: Syntax of a struct and Access Modifiers for structs


In C#, struct is the user-defined value data type that represents data structures. It can obtain a parameterized
constructor, static constructor, constants, fields, methods, properties, indexers, operators, events, and nested
types. All elements of a structure are private by default.
Example 1.13:

using System;
namespace Class_Demos {
public struct StDemo {
public int x;
public string y;

public StDemo(int a, string b){


x = a;
y = b;
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 12 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP

Continued . . .
public void Display(){
Console.WriteLine("\n X= {0} \n Y= {1}", x, y);
}
}
class StructDemo {
static void Main(){
StDemo st=new StDemo();
st.x = 10;
st.y = "Hello";
Console.WriteLine("X= {0}, \nY={1}", st.x, st.y);

//Initialize default value


StDemo st1 = new StDemo(200,"Good Morning");
st1.Display();

// another way of creating structure variable


StDemo s3;
s3.x = 500;

Console.WriteLine("x=" + s3.x);
Console.WriteLine("Please enter to QUIT....");
Console.ReadLine();

}
}
}

1.15 System.Object Class:


The Object class is the base class of all the classes in C#. It has the following methods:
Table 3.5: List of methods for knowing about objects

Method Description
Determines whether the specified object is equal to the current
Equals(Object)
object.
Equals(Object, Determines whether the specified object instances are considered
Object) equal.
Finalize() Allows an object to try to free resources.
GetHashCode() default hash function.
GetType() Type of the current instance.
MemberwiseClone() shallow copy of the current Object.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 13 | 34


Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP

ReferenceEquals(Object,Object) Determines whether the specified Object instances are the


same instance.
ToString() Returns a string that represents the current object.

Example 1.14:

using System;
class ObjectType
{
int x = 10;

ObjectType ShallowCopy()
{
return (ObjectType)MemberwiseClone();
}
~ObjectType()
{
Console.WriteLine("Finalize() method performs");
}

static void Main()


{
ObjectType ob1 = new ObjectType();
ObjectType ob2 = new ObjectType();

Console.WriteLine("Is objects type are Equal ? -> " +


ob1.Equals(ob2));

ob1 = ob2;
Console.WriteLine("Is objects type are Equal ? -> " +
Equals(ob1,ob2));

Console.WriteLine("Type is ->" + ob1.GetType());


Console.WriteLine("Hash Details is ->" + ob1.GetHashCode());

int i = 20;
Console.WriteLine(i.GetType());

ObjectType ob3 = ob2.ShallowCopy(); // For member wise clone


Console.WriteLine("After cloned: Is objects type are Equal?
-> " + ReferenceEquals(ob3, ob2));

Console.ReadLine();
}
}
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 14 | 34


Module -2 Chapter - 2: Encapsulation
Chapter – 2

Encapsulation

Introduction:
C# is an Object oriented Programming language. So, like all Object oriented languages, C# will also supports
following Object Oriented Principles.
i. Encapsulation : How does this language hide an object’s internal implementation?
ii. Inheritance : How does this language promote code reuse?
iii. Polymorphism : How does this language let you treat related objects in a similar way?

2.1. Encapsulation:
Encapsulation is the procedure of covering up of data and functions into a single unit. An encapsulated object
is often called an abstract data type.
We need of Encapsulation for the following reasons:
▪ One of the fundamental principles of object-oriented programming.
▪ A process of hiding all the internal details of an object from the outside world.
▪ Provides a way to protect data from accidental corruption.
▪ Gives the ability to validate the values before the object user change or obtain the value.
▪ Makes implementation inaccessible to other parts of the program and protect from whatever
actions might be taken outside the function or class.

2.2. Encapsulation using accessors and mutators:


Rather than defining the data in the form of public, we can declare those fields as private so that we achieved
encapsulation. The Private data are manipulated using accessor (get: store the data to private members) and
mutator (set: to interact with the variable) methods.
Syntax: set { <accessor-body> }
get { <accessor-body> }

Note: Keep in mind about property


 Although you don’t have to have both a getter and a setter, you must have one of the two.
 A property defined with both a getter and a setter is called a read-write property.
 A property defined with only a getter is called a read-only property.
 A property defined with only a setter is called a write-only property.

The Private data are manipulated indirectly by two ways.


i. Traditional accessor and mutator methods. ii. Named property

i. The first method is, if we want the outside world to interact with private usn data field, tradition
dictates defining an accessor (get method) and mutator (set method).
Example 2.1: In this application, we have defined two methods set() and get(). The set() method
mutator, set the value of usn variable. The get() method accessor, displays the value of the usn variable
on the command prompt.
Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 15 | 34
Module -2 Chapter - 2: Encapsulation

using System; class GetSetDemo {


namespace Chapter4_Examples { static void Main(){
class Student { Student st1 = new Student();
string name, branch,usn; st1.setusn("1RX12MCA01");
public void setusn(string sid){ Console.WriteLine("USN: "
usn = sid; +st1.getusn());
} Console.ReadKey();
public string getusn(){ }
return usn; }
} }
}

ii. Another method is using a named property.


Example 2.2:
using System; class GetSetDemo1 {
namespace Chapter4_Examples{ static void Main(){
class Student{ Student st1 = new Student();
string name, branch, usn; st1.Studusn ="1RX12MCA01";
Console.WriteLine("USN: "
public string Studusn{
+st1.Studusn);
set{ usn = value; }
Console.ReadKey();
get{return usn;}
}
}
}
} }
In the above example, we see the usage of Encapsulation by using properties. The property is composed using
a get block(accessor) and set block(Mutator). The get block returns the value of the some property field. The
set block sets the value of the some property field with the contents of “value” token.
NOTE: In the C# “value” keyword represents the right hand side of the assignment. The underlying data type
of the value token depends on which sort of data it represents so that “value” token is called as object.

2.3. Encapsulation using Properties:


i. Write-Only Property: Properties can be made write-only. This is accomplished by having only a set
mutator in the property implementation.
Example 2.3: class Student{
string name, branch, usn; In this example, the property “Studusn”
public string Studusn{ is having only set (mutator) but not get
set{usn = value;} (accessor). So Studusn can called as a
} “write-only property”.
}

ii. Creating Read-Only Fields: Properties can be made read-only. This is accomplished by having only
get accessor in property implementation.
Example 2.4: In the below example, the property “Studusn” is having only get (accessor) but not set
(mutator). So can call Studusn as a “read-only property”.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 16 | 34


Module -2 Chapter - 2: Encapsulation

using System; class ReadOnly{


namespace Class_Demos{ static void Main(){
class Student{ Student st1 = new Student();
string studusn; Console.WriteLine("USN: "
public Student(){ + st1.Studusn);
studusn="1RX12MCA01"; Console.ReadKey();
} }
public string Studusn{ }
get{ }
return studusn;
}
}
}

iii. “static” property: C# also supports “static” properties. The static members are accessed at the class
level, not from an instance (object) of that class. Static properties are manipulated in the same manner
as static methods, as seen here:
Example 2.5: Assume that the Student type defines a point of static data to represent the name of the
institution studying these students. You may define a static property as follows:
using System; class StaticProperty{
namespace Class_Demos{ static void Main(){
class Student{ Student.Institution = "RNSIT";
string name, branch, usn; Console.WriteLine("InstitutionName:"
static string instName; +Student.Institution);
public static string Institution Console.ReadKey();
{ }
set { instName = value; } }
get { return instName; } }
}
}

2.4. Inheritance:
The next pillar of OOP, Inheritance provides you to reuse existing code and fast implementation time. The
relationship between two or more classes is termed as Inheritance.
In essence, inheritance allows to extend the behavior of a base (or parent/super) class by enabling a subclass to
inherit core functionality (also called a derived class/child class). All public or protected variables and methods
in the base class can be called in the derived classes.
Inheritance comes in two ways:
 Classical inheritance ( “is-a” relationship)
 Containment/delegation model (“has-a” relationship).

Classical inheritance (“is-a” relationship):


When “is-a” relationship have established between classes, we are building a dependency between types. The
basic idea behind classical inheritance is that new classes may extend the functionality of other classes.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 17 | 34


Module -2 Chapter - 2: Encapsulation
Example 2.6: Assume that we wish to define two additional classes to model Animal and
Dog. The hierarchy looks like as shown below and we notice that Animal “is-a” Mammal, Mammal
Dog IS-A Animal; Hence dog IS-A mammal as well.
Animal
In “is-a” model, base classes are used to define general characteristics that are common to
all subclasses and classes are extended by using “:” operator. The derived classes inherit Dog
the base class's properties and methods and clients of the derived class have no knowledge
of the base class.
using System;
class Animal { class isademo{
public Animal(){ static void Main(){
Console.WriteLine("Base class constructor"); Dog d = new Dog();
} d.Greet();
public void Greet(){ Console.ReadKey();
Console.WriteLine("Hello,I am kind of Animal"); }
} }
}
class Dog : Animal{
public Dog(){
Console.WriteLine("Derived class constructor");
}
}
In the above example, when the object d is created for the class Dog; the default constructor of a base class
Animal is called automatically before the logic of the custom Dog constructor is executed. You will notice that
even though we have not defined a Greet() method for the Dog class, it still knows how to greet us, because it
inherits this method from the Animal class.
Do be aware that inheritance preserves encapsulation. Therefore, a derived class cannot directly access the
private members defined by its base class.

Containment / Delegation model (“Has-A”):


The “HAS-A” relationship specifies how one class is made up of other classes.
Example 2.7: Consider we have two different classes Engine and a Car when both of these entities share each
other’s object for some work and at the same time they can exists without each other’s dependency (having their
own life time) and there should be no single owner both have to be an independent from each other than type
of relationship is known as "has-a" relationship i.e. Association.
using System; class hasademo{
class Engine{ static void Main(){
public int horsepower; Console.WriteLine("Manufacturing a Car");
public void start(){ Car mycar = new Car();
Console.WriteLine("Engine Started!"); mycar.make = "Toyoto";
Console.WriteLine("Manufacturing a Engine to start car");
} }
mycar.eng = new Engine();
class Car{
mycar.eng.horsepower =220;
public string make;
Console.WriteLine("\n***Car Details***");
public Engine eng; //Car has an Engine Console.WriteLine("Brand:"+ mycar.make);
public void start(){ Console.WriteLine("Power: "+ mycar.eng.horsepower);
eng.start(); mycar.start();
} } Console.Read();
} }

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 18 | 34


Module -2 Chapter - 2: Encapsulation
Inheritance is of four types, which are as follows:
i. Single Inheritance: Refers to inheritance in which there is only one base class and one derived class.
This means that a derived class inherits properties from single base class.
ii. Hierarchical Inheritance: Refers to inheritance in which multiple derived classes are inherited from
the same base class.
iii. Multilevel Inheritance: Refers to inheritance in which a child class is derived from a class, which in
turn is derived from another class.
iv. Multiple Inheritance: Refers to inheritance in which a child class is derived from multiple base class.

C# supports single, hierarchical, and multilevel inheritance because there is only a single base class. It does not
support multiple inheritance directly. To implement multiple inheritance, you need to use interfaces.
Example 2.8:
InherDemo.cs class InherDemo{
static void Main(){
using System; //Create a Base Class Object
namespace Class_Demos{ Console.WriteLine("I'm accessing Base Class Object");
class BaseClass{ BaseClass bc = new BaseClass();
public int dm; bc.dm = 10;
public void BCMethod(){ bc.BCMethod();
Console.WriteLine("I'm a Base Class Method"); //Create a Derived Class Object
} Console.WriteLine("I'm accessing Derived Class Object");
} DerivedClass dc=new DerivedClass();
class DerivedClass:BaseClass{ dc.dm = 20;
public void DCMethod(){ dc.BCMethod();
Console.WriteLine("I'm a Derived Class Method"); dc.DCMethod();
} Console.WriteLine("\nPress ENTER to quit...");
} Console.Read();
}
}
}

In this section, you learn about the following topics in the context of inheritance:
▪ Inheritance and Constructors ▪ Extension methods
▪ Sealed classes and sealed methods

2.5. Inheritance and Constructors:


As you know, a constructor is a special method of a class, which is used to initialize the members of the same
class. A constructor is called by default whenever an object of a class is created.

It is important to note that a Base class constructors are not inherited by derived classes. Thus cannot instantiate
a base constructor using derived class object, so we need the “base” keyword to access constructor of the base
class from within a derived class.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 19 | 34


Module -2 Chapter - 2: Encapsulation
Example 2.9:

using System;
namespace Chapter4_Examples{
public class A { // It is the base class.
protected int x;
public A(int i){
x = i;
Console.WriteLine("Base constructor A()");
}
}
public class B : A{ // This class derives from the previous class
int y;
public B(int i, int j): base(i){
y = j;
Console.WriteLine("Derived constructor B()");
}
public void show(){
Console.WriteLine("X= {0} \nY= {1}", base.x, y);
}
}
class Basekeydemo {
static void Main(){
B b = new B(10, 20);
b.show();
Console.ReadKey();
}
}
}

2.6. Sealed Classes and Sealed Methods:


Sealed classes are classes that cannot be inherited. You can use the “sealed” keyword to define a class as a
sealed class.
Syntax: sealed class <Class_name>{
// data mebers and member functions
}

The following code snippet shows how to define a sealed class:


sealed class MyClass{ Class MainClass{
. . . // data mebers //Instantiation of
public void GetDetail(){ myclass class
//Code //Method calling
} }
public void ShowDetail(){
//Code
}
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 20 | 34


Module -2 Chapter - 2: Encapsulation
When a base class is declared with sealed keyword, then that class cannot be extended. The sealed modifiers is
used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another
class, as shown in the following code snippet: class DerivedClass: MyClass{} //Error

You will get the error


message:

A sealed class can contain sealed methods. Similar to the sealed class, sealed method are also defined using
the “sealed” keyword. A derived class cannot override the sealed methods; however, you can use a sealed
method to override an inherited virtual method with the same signature. It means that in methods, you always
use sealed keyword with the combination of override keyword, as shown in the following code snippet:

class BaseClass{ Here, the sealed method


public virtual void SealedMethod(){
//Method Body SealedMethod() overrides the
} virtual method SealedMethod()
} defined in BaseClass class. Any
class DerivedClass: BaseClass{ derived class of DerivedClass
public sealed override void SealedMethod(){
class cannot further override the
//Method Body
} SealedMethod() method.
}

Example 2.10:
using System;
namespace Class_Demos{
sealed class BClass{
public void method1(){
Console.WriteLine("This is method of Base class");
}
}
//Following lines shows compiler error as sealed class cannot be inherited
class DClass : BClass{
//Code
}
class SealedDemo{
static void Main(){
BClass obj = new BClass();
obj.method1();
Console.WriteLine("\nPress ENTER to quit...");
Console.Read();
}
}
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 21 | 34


Module -2 Chapter - 2: Encapsulation
2.7. Extension methods
Extension method is a method that helps you to extend a class without creating a new derived class or
modifying the original class. It works as a static method, but is invoked with an instance of the extended class.
The extension method can be any static method which uses the “this” keyword before its first parameter.
Example 2.11:

using System;
namespace Class_Demos{
public static class Myclass{
//Defining extension method with
public static int myExtensionmethod(this string num){
return (Int32.Parse(num));
}
public static int Mystaticmethod(string num){
return (Int32.Parse(num));
}
}
class ExtensionDemo{
static void Main(){
string num = "100";
//invoking method of type extension
int ext = num.myExtensionmethod(); //Line A
Console.WriteLine("The output from myExtensionMethod()”+ext);

//invoking method of type static


int stat = Myclass.Mystaticmethod(num); //Line B
Console.WriteLine("The output from mystaticMethod()"+ stat);
Console.Read();
}
}
}

Differences between an extension method and a static method are as follows:

Extension Method Static Method


Do not contain the this keyword in their argument
Contain this keyword before the first argument
declaration
When an extension method is called, the argument When a static method is called, you must pass all
declared with the “this” keyword is not passed. the arguments. (see Line B in Program)
(see Line A in program)
Extension method are defined in a static class only. It is not necessary that the static methods are
declared in a static class only

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 22 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism
Chapter – 3

Polymorphism

The final pillar of OOP is polymorphism. Polymorphism means “one name many forms”.
Polymorphism defined as “one object behaving as multiple forms and one function behaves in different
forms”. In other words, “Many forms of a single object is called Polymorphism”.

Advantages:
• Allows you to invoke methods of a derived class through base class reference during runtime
• Provides different implementations of methods in a class that are called through the same name

There are two types of polymorphism, which are as follows:


i. Static polymorphism/Compile Time polymorphism/Early Binding/Overloading
ii. Dynamic polymorphism/Run-time polymorphism/Late Binding/Overriding

3.1 Compile Time Polymorphism / Overloading:


When a compiler compiles a program, it knows the information about the method arguments and accordingly,
it binds the appropriate method to an object at the compile time itself. This process is called as Static
polymorphism/Compile Time polymorphism/Early Binding/Overloading.

You can implement compile time polymorphism through overloaded methods in three types that are mention
below:
i. Method overloading ii. Operator overloading iii. Indexer overloading

i. Method overloading:
In method overloading, can be define many methods with the same name but different signatures. A method
signature is the combination of the method’s name along with the number, type, and order of the parameters.

Example 3.1: In this application, the Area() method of Shape class is overloaded for calculating the area of
square, rectangle, circle and triangle shapes. In the Main() method, the Area() method is
called multiple times by passing different arguments.

using System;
namespace Class_Demos{
class Shape{
public void Area(int side){
Console.WriteLine("The area of Square is: " + side * side);
}
public void Area(int length, int breadth){
Console.WriteLine("The area of Rectangle is: "
+ length * breadth);
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 23 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism

public void Area(double radius){


Console.WriteLine("The area of Circle is: "
+ 3.14 * radius * radius);
}
public void Area(double base1, double height){
Console.WriteLine("The area of Squate is: "
+ (base1 * height)/2);
}
}
class MOverload{
static void Main(){
Shape shape = new Shape();
shape.Area(15);
shape.Area(10, 20);
shape.Area(10.5);
shape.Area(15.5, 20.4);
Console.Read();
}
}
}

ii. Operator Overloading:


The mechanism of assigning a special meaning to an operator according to user defined data type, such as
classes or structs, known as operator overloading. The below table shows the list of operators and overloading
status.
Table 3.1: operators and their overloading status
Operators Type Overloading Status
+, - , !, ++, --, true, false Unary Can be overloaded
+, - , *, /, %, &, |, ^, <<, >> Binary Can be overloaded
= =, !=, <, >, <=, >= Comparison Can be overloaded
&&, | | Conditional Logic Cannot be overloaded
Cannot be overloaded but can help in
[] Array Indexing
defining indexes
Cannot be overloaded but can help in
() Cast
defining new conversion operators
+=, -=, *=, /=, %=, |=, ^=, <<=, >>= Assignment Cannot be overloaded
=, ⚫, ?:, ->, new, is, sizeof, typeof other Cannot be overloaded

When overload an operator, you need to create a method that must be preceded by the “operator” keyword and
that method should define as a static method.
Example 3.2: In this application, we have created a class, UnaryOpr, which contains a constructor,
UnaryOpr, to initialize its two variables. The UnaryOpr class also contains the ShowData() method to
display the value of the class variables and overload the functionality of the – (minus) operator. The – operator
is overloaded by using the operator keyword. Next in the Main()method of the OpOverload class, the –
operator is used to show the negative value of an object of the UnaryOpr class.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 24 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism

using System;
class unaryopr{
int n1, n2;
public unaryopr() { }
public unaryopr(int a, int b){
n1 = a;
n2 = b;
}
public void showData(){
Console.WriteLine("The numbers are: " +n1+ " and " +n2);
}
public static unaryopr operator -(unaryopr opr){
unaryopr obj = new unaryopr();
obj.n1 = -opr.n1;
obj.n2 = -opr.n2;
return obj;
}
}
class OpOverload{
static void Main(){
unaryopr opr1 = new unaryopr(20,30);
Console.WriteLine("Before Operator Overloading");
opr1.showData();
unaryopr opr2 = new unaryopr();
opr2 = -opr1; //invoke operator overloading method
Console.WriteLine("After Operator Overloading");
opr2.showData();
Console.Read();
}
}

Example 3.3: In this application, we have created a class, BinaryOpr, which contains a constructor,
BinaryOpr, to initialize its two variables. The BinaryOpr class also contains the ShowData() method to
display the value of the class variables and overload the functionality of the + (addition) operator. The +
operator is overloaded by using the operator keyword. Next in the Main()method of the OpOverload1
class, the + operator is used to show the addition of the values of the objects of the BinaryOpr class.

using System;
namespace Class_Demos{
class Binaryopr{
int n1, n2;
public Binaryopr() { }
public Binaryopr(int a, int b){
n1 = a;
n2 = b;
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 25 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism

public void showData(){


Console.WriteLine("The numbers are: " + n1 + " and " + n2);
}
public static Binaryopr operator +(Binaryopr opr1, Binaryopr opr2){
Binaryopr obj = new Binaryopr();
obj.n1 = opr1.n1 + opr2.n1;
obj.n2 = opr1.n2 + opr2.n2;
return obj;
}
}
class BOverload{
static void Main(){
Binaryopr opr1 = new Binaryopr(20, 30);
opr1.showData();

Binaryopr opr2 = new Binaryopr(30, 40);


opr2.showData();
Binaryopr opr3 = new Binaryopr();
opr3 = opr1 + opr2; //invoke operator overloading method

opr3.showData();
Console.Read();
}
}
}

iii. Indexer Overloading:


An indexer is used to treat an object as an array. It is used to provide index to an object to obtain values from
the object.
➢ Implementing an indexer requires you to use brackets ([ ]) with an object to get and set a value of the
object.
➢ Indexer are declared as properties, with the difference that in case of indexers, you do not need to provide
name to them. You need to use the “this” keyword to define an indexer.
Example 3.4:
using System; public string this[int position]{
namespace Class_Demos{ set{ mydata[position] = value; }
class MyClass{ get{return (mydata[position]); }
string[] mydata; }
int arrsize; public string this[string data]{
public MyClass(int size){ set{
arrsize = size; for (int i=0; i<arrsize; i++){
if (mydata[i] == data)
mydata = new string[size];
mydata[i] = value;
for (int i = 0; i < size; i++) }
mydata[i] = "DataValue"; }
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 26 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism

Continued...
get{
int count = 0;
for (int i = 0; i < arrsize; i++){
if (mydata[i] == data)
count = count + 1;
}
return count.ToString();
}
}
}
class IndOverload{
static void Main(){
int size = 10;
MyClass obj=new MyClass(size);

obj[1] = "Hello";
obj[3] = "Good Morning";
obj[7] = "Welcome";
obj["DataValue"] = "Have a nice day";

for (int i = 0; i < size; i++)


Console.WriteLine("obj[{0}]: {1}", i, obj[i]);

Console.WriteLine("\n\nNumber of \"Have a nice day\"entries:{0}",


obj["Have a nice day"]);
Console.Read();
}
}
}

In this snippet, we have overloaded indexers by passing different type of parameters. We have defined two
indexers, with the int type and string type parameters, named position and data, respectively. These
indexers are used to display the values of different string data that is passed in the Main() method of the
IndOverload class.

3.2 Runtime Polymorphism/Overriding:


Overriding is a feature that allows a derived class to provide a specific implementation of a method that is
already defined in a base class. The implementation of method in the derived class overrides or replaces the
implementation of method in its base class. This feature is also known as runtime polymorphism because the
compiler binds a method to an object during the execution of a program (runtime) instead of during the
compilation of the program.

When a method get called, the method defined in the derived class is invoked and executed instead of the one
in the base class.

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 27 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism
To invoke the method of a derived class that is already defined in the base class, you need to perform the
following steps:
➢ Declare the base class method as virtual
➢ Implement the derived class method using the override keyword
Example 3.5: We have created Bclass and Dclass classes, where the Dclass class is the derived class
of the Bclass class. The Bclass class contain virtual method Show(). The Dclass class is overriding
the Show() method of the base class by using the override keyword.
using System; class PolyDemo{
namespace Chapter4_Examples{ static void Main(string[] args){
public class Bclass{ // calling the overriden method
public virtual void Show(){ Dclass objDc = new Dclass();
Console.WriteLine("Base Class"); objDc.Show();
}
// calling the base class method
} Bclass objBc = new Bclass();
class Dclass : Bclass{ objBc.Show();
public override void Show(){
Console.WriteLine("Derived Class"); //Calling the overriden method because preference
} will be right hand of assignment operator
} Bclass obj = new Dclass();
obj.Show();
Console.ReadLine();
}
}
}

Consider, you want to derive a class from a base class and to redefine some methods contained in this base
class. In such a case, you cannot declare the base class method as virtual.

Then, how you can override a method without declaring that method as virtual in the base class?
Ans: This can be possible with the new operator. The new operator is used to override the base class method
in the derived class without using the virtual keyword. The new operator tells the compiler that the
derived class method hides the base class method.
Example 3.6:
using System; class PolyDemo1{
namespace Class_Demos{ static void Main(string[] args){
public class Bclass{ // calling the overriden method
public void Show(){ Dclass objDc = new Dclass();
Console.WriteLine("Base Class"); objDc.Show();
} // calling the base class method
} Bclass objBc = new Bclass();
class Dclass : Bclass{ objBc.Show();
public new void Show(){
//Calling Base Class Method
Console.WriteLine("Derived Class"); objBc = new Dclass();
} objBc.Show();
} Console.ReadLine();
}
}
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 28 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism
3.3 Abstraction:
Abstraction is the process of hiding the details of a particular concept or object from a user and exposing only
the essential features.
The characteristics of abstraction are as follows:
➢ Managing the complexity of the code ➢ Decomposing complex systems into smaller components
Let’s learn about the abstract classes and methods in detail.

3.4 Abstract Classes:


Classes can be declared as abstract by putting the keyword “abstract” before the class definitions.
The main purpose of the Abstract classes is to make classes that only represent base classes, and don’t want
anyone to create objects of these class types. An abstract class cannot be instantiated because cannot create an
object of the class.
Example: public abstract class Shape{
//Class Definition Shape obj=new Shape();
} //Can’t be instantiated

An abstract class can contain either


Example:
abstract methods or non-abstract methods. public abstract class Shape{
Abstract members do not have any public abstract void Draw();
implementation in the abstract class, but public void NonAbstractMethod(){
the same has to be provided in its derived Console.WriteLine("NonAbstract Method");
}
class. }
Characteristics:
❖ Restricts instantiation, implying that you cannot create an object of an abstract class.
❖ Allows you to define abstract as well as non-abstract members in it
❖ Requires at least one abstract method in it
❖ Restrict the use of sealed keyword
❖ Possesses public access specifier; therefore, it can be used anywhere in a program.

3.5 Abstract methods:


Abstract methods have no implementation, so the method
Syntax: definitions is followed by a semicolon instead of a normal
public abstract void Draw(); method block. Derived classes of the abstract class must
implement all abstract methods.

Characteristics:
❖ Restricts its implementation in an abstract derived class
❖ Allows implementation in a non-abstract derived class
❖ Requires declaration in an abstract class only
❖ Restrict declaration with static and virtual keywords
❖ Allows you to override a virtual method.
Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 29 | 34
Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism
Example 3.7:
using System;
namespace Chapter4_Examples{
abstract class absClass{
//A Non abstract method
public int AddTwoNumbers(int Num1, int Num2){
return Num1 + Num2;
}
//An abstract method to be overridden in derived class
public abstract int MultiplyTwoNumbers(int Num1,int Num2);
}

//A Child Class of absClass


class absDerived:absClass{
//using override keyword,implementing the abstract method MultiplyTwoNumbers
public override int MultiplyTwoNumbers(int Num1,int Num2){
return Num1 * Num2;
}
}
class AbstractDemo{
static void Main(string[] args){
absDerived calculate = new absDerived();
int added = calculate.AddTwoNumbers(10,20);
int multiplied = calculate.MultiplyTwoNumbers(10,20);
Console.WriteLine("Added : {0}, Multiplied : {1}", added, multiplied);
Console.ReadLine();
}
}
}

3.6 Interfaces:
“An interface is a collection of methods, events, properties and indexers, but it does not implement them”.
Interface are introduced to provide the feature of multiple inheritance to classes.
Multiple inheritance is the feature of OOP
which allows a class to inherit from interface <Interface_Name> {
multiple classes. The methods defined in
an interface do not have implementation, //Abstract method declaration in interface body
they only specify the parameters that they }
will take and the types of values they will
return.
Example: public interface Channel
{
void Next();
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 30 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism
Characteristics:
❖ An interface is always implemented in a class.
❖ The class that implements the interface needs to implement all the members of the interface.
❖ Cannot instantiate an object through an interface
❖ An interface can have the same access modifiers as a class, such as public and private.

To implement multiple inheritance in a program, you need to use interfaces.


Example 3.8: Create an application named InterfaceDemo that shows how to implement an interface
in a class.
using System; class InterfaceDemo:Channel, Book{
namespace Class_Demos{ void Channel.Next(){
public interface Channel{ Console.WriteLine("Channel Next");
void Next(); }
void Previous(); void Book.Next(){
} Console.WriteLine("Book Next");
public interface Book{ }
void Next(); public void Previous(){
void Chapter(); Console.WriteLine("Previous");
} }
public void Chapter(){
Console.WriteLine("Chapter");
}
static void Main(){
InterfaceDemo ind = new InterfaceDemo();
((Book)ind).Next();//invoking Book method
ind.Previous();
ind.Chapter();
Console.Read();
}
}
}

3.7 Implementation of Interfaces and Inheritance:


When an interface is implemented by a base class, then the derived class of the base class automatically inherits
method of the interface. You can initialize an object of the interface by type casting the object of the derived
class with the interface itself.

Example 3.9: We have created two interface BaseInterface and DerivedInterface. The
BaseInterface interface is inherited by the DerivedInterface interface. Then the
InterfaceImplemeter class implements the DerivedInterface interface.

using System;
namespace Class_Demos{
interface BaseInterface{
void GetPersonalDetail();
void GetContactDetail();
}
interface DerivedInterface:BaseInterface{
void ShowDetail();
}
Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 31 | 34
Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism

class InterfaceImplementer : DerivedInterface{


string name;
long phonenum;
public void GetPersonalDetail(){
Console.WriteLine("Enter your Name");
name = Console.ReadLine();
}
public void GetContactDetail(){
Console.WriteLine("Enter your Phone Number");
phonenum = int.Parse(Console.ReadLine());
}
public void ShowDetail(){
Console.WriteLine("\nYour Details:");
Console.WriteLine("Name: " + name);
Console.WriteLine("Phone Number: " + phonenum);
}
}
class InterfaceDemo1{
static void Main(){
InterfaceImplementer Myobj = new InterfaceImplementer();
Myobj.GetPersonalDetail();
Myobj.GetContactDetail();
Myobj.ShowDetail();

Console.ReadLine();
}
}
}

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 32 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism
Questions:

Chapter 1- Classes, Objects, and Object Oriented Programming


1. What do you mean by ‘this’ keyword? Explain with suitable examples. 05
2. Describe how to create an array of objects to the class with suitable example. 05
3. Explain how to defining partial class and partial method with an example. 10
4. List the various access modifiers available in C#, with description of each. 05
5. Explain the concept of static methods and static data with suitable examples. 10
6. What is properties? Explain different ways of manipulate the private data with an example. 10
7. Differentiate a property and static property 8
8. What is an indexer? Give an example. Differentiate indexer and property. 10
9. Write a Short notes:
i. Static Class ii. Static property iii. Read-only property
ii. Value token

Chapter 2 - Encapsulation
1. • What are the three pillars of object oriented programming in C#? What are the two ways of
enforcing encapsulation? Give examples for both the methods.
• How do you enforce encapsulation using accessors and mutators, class properties and static
properties?
• What are the different methods of accessing private data fields by other classes in C#?
Explain with examples. 10
2. How do you prevent inheritance using sealed classes? Explain with an example. 5
3. Bring out the differences between interfaces and abstract base classes. 5
4. Explain with an example:
8
i. public class ii. sealed class and sealed method iii. Abstract class
5. With an example, explain Extension method. 6

Chapter 3 – Polymorphism
1. What is a polymorphism? List types of polymorphism. 4
2. Explain the overloading of equality and comparison operators in C# 6
3. What are abstract classes and abstract methods? Explain with an example. 5
4. Write a program to overload + and – operators for adding and subtracting two square matrices. 10
5. Write a C# program, which defines class Flight. The class Flight implements two interfaces
namely Ibirds and Iplane and the interface member of Ibirds and Iplane is fly(), which displays 08
some message. Write the usage class which exercises the above.
6. Write a short notes:
5
i. Static data ii. Operator overloading

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 33 | 34


Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism

7. Create a class called student which contains, USN, studentName and also total marks obtained.
Also overload comparison operators for comparing two students based upon their total marks 10
obtained.
8. What is the alternate approach to support multiple inheritance in C# .NET? List its major features
10
with code example.
9. What is Interface? Explain how to create interfaces and implemented with an example. 8
10. Distinguish between compile time and runtime polymorphism with suitable example. 8

Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 34 | 34

You might also like