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

C# Module 2

1. The document discusses object-oriented programming concepts in C# such as classes, objects, methods, properties, and access modifiers. 2. It explains how to create classes and objects, use methods as class members, and pass objects as arguments. 3. The document also covers creating arrays of objects, using the "this" keyword, returning values from methods, and defining partial classes and methods.

Uploaded by

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

C# Module 2

1. The document discusses object-oriented programming concepts in C# such as classes, objects, methods, properties, and access modifiers. 2. It explains how to create classes and objects, use methods as class members, and pass objects as arguments. 3. The document also covers creating arrays of objects, using the "this" keyword, returning values from methods, and defining partial classes and methods.

Uploaded by

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

Programming using C# .

NET

Mr. Prashant Ankalkoti


Asst.Prof, Dept. Of MCA
J N N C E, Shivamogga.
Email : [email protected]
Mob : 9886363246 1
Module 2
Classes, 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.

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 2


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.
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 3
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. The body of the
class contains class members that
can include constants, fields (or
variables), methods, properties,
indexers, events, operators, and
nested types.
Nested types are defined by class,
interface, delegate, struct, or
enum declarations within the class
body.
4
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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:

5
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.
Note:
• To access the instance members of a class, use dot( ) operator
• Cannot be used with static members because static members are accessed by a
class and not by the instance of the class.
Syntax:

6
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
7
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.
Example: Employee[] manager = new Employee[size];
Note: you cannot create an array and its individual elements simultaneously.
Syntax:

8
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

9
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
10
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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 source files. All the source files, each containing a section of
class definition, combine when the application is complete. You may need a partial
class when developers are working on large projects.
A partial class distributes a class over multiple separate files; allowing developers to
work on the class simultaneously. You can declare a class as partial by using the
“partial” keyword.
All the divided sections of the partial class must be available to form the final class
when you compile the program. All the section must have the same accessibility
modifiers, such as public or private.
11
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
12
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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
 Deals with implementing the partial method declaration
Rules:
 Must have a void return type
 No access modifier are allowed for declaring a partial method except for static.
 Partial methods are private by default.

13
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
14
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

15
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
16
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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

17
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.
18
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

19
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
20
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.
21
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

22
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
23
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

24
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.
25
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
1.11 Properties:
A property is a member that provides a flexible mechanism to read, write or compute
the value of a private field. You can implement properties with the type-safe get and set
methods.
The important thing is the “value” keyword, sets the value of the some property field
with the contents of value token.

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.
26
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.
27
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

28
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Example 1.10: using System;
namespace Chapter4_Examples{
class Student {
Static properties are manipulated in the same string name, branch, usn;
static string instName;
manner as static methods, as seen here: public static string Institution{
For example, assume that the Student type set { instName = value; }
get { return instName; }
defines a point of static data to represent the }
name of the institution studying these }
class GetSetStatic {
students. You may define a static property as static void Main(){
follows: Student.Institution = “JNNCE";
Console.WriteLine("Institution
Name: "+Student.Institution );
Console.ReadKey();
}}}
29
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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 :

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.
30
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
class Student {
string[] usn = new string[3];
public string this[int index]{ Indexers have the following additional features:
set { usn[index] = value; }
• Inheritance – Allows inheritance, which means a derived class
get {
if (index < 0 || index >= usn.Length) can inherit a base class indexer.
return null;
else However, modifiers such as virtual and override are used at the
return (usn[index]);
property level, not at the accessor level.
}
}} • Polymorphism – Allows polymorphism, which means the
class IndexerDemo {
public static void Main(){ derived class can override a base class indexer.
Student slist = new Student();
• Uniqueness – Provides a signature that uniquely identifies an
slist[0] = "1JN12MCA01";
slist[1] = "1JN12MCA02"; indexer.
slist[2] = "1JN12MCA03";
for (int i = 0; i < 3; i++) • Non – Static – Indexer cannot be static. If you declare, the
Console.WriteLine(slist[i]);
compiler generates an error.
Console.ReadKey();
}
}} Example 1.11:
31
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
32
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
33
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
34
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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?

Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 35


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.
36
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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:

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.
37
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
• The Private data are manipulated indirectly by two ways.
i. Traditional accessor and mutator methods.
ii. Named property
• 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.

38
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
39
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
40
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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:

In this example, the property “Studusn” is having only set (mutator) but not get
(accessor). So Studusn can called as a “write-only property”.

41
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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”.

42
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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 Student{
string name, branch, usn;
static string instName;
public static string Institution
{
set { instName = value; }
get { return instName; }
}}
class StaticProperty{
static void Main(){
Student.Institution = “JNNCE";
Console.WriteLine("InstitutionName:“+Student.Institution)
;
Console.ReadKey();
}}
43
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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).
44
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.
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 the base class's properties and methods and clients of the derived class have no
knowledge of the base class.

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, Dog IS-A Animal; Hence dog IS-A mammal as well.
45
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.
46
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

47
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
48
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

49
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
50
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

51
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
52
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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:

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

53
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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:
54
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Here, the sealed method SealedMethod() overrides the virtual method SealedMethod()
defined in BaseClass class. Any derived class of DerivedClass class cannot further
override the SealedMethod() method.

55
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
56
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
using System;
2.7. Extension methods public static class Myclass{
Extension method is a method that //Defining extension method with
public static int myExtensionmethod(this string num) {
helps you to extend a class without return (Int32.Parse(num));
}
creating a new derived class or public static int Mystaticmethod(string num) {
return (Int32.Parse(num));
modifying the original class. It works as }}
class ExtensionDemo{
a static method, but is invoked with an static void Main(){
instance of the extended class. string num = "100";
//invoking method of type extension
The extension method can be any int ext = num.myExtensionmethod(); //Line A
Console.WriteLine("The output from
static method which uses the “this” myExtensionMethod()”+ext);
//invoking method of type static
keyword before its first parameter. int stat = Myclass.Mystaticmethod(num); //Line B
Console.WriteLine("The output from mystaticMethod()"+ stat);
Example 2.11: Console.Read();
}} 57
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
58
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE 59
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

60
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.
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.
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.

61
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
62
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
63
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
64
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

65
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
66
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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();
}}
67
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

68
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

69
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
70
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

71
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
72
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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:
i) Managing the complexity of the code ii) Decomposing complex systems into smaller
components

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.
73
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
74
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

75
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
3.5 Abstract methods:
Abstract methods have no implementation, so the method definitions is followed by a
semicolon instead of a normal 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.

76
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
77
3.6 Interfaces:
“An interface is a collection of data members and member functions, 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
multiple classes. The methods defined in an interface do not have implementation,
they only specify the parameters that they will take and the types of values they will
return.
Example:

78
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

79
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
Example 3.8: Create an application named InterfaceDemo that shows how to
implement an interface in a class.

80
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
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.

81
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE
82
Mr. Prashant Ankalkoti, Faculty, MCA Dept., JNNCE

You might also like