0% found this document useful (0 votes)
5 views20 pages

UNIT 3 Notes - 2023-24 3rd Sem

This document discusses the pillars of Object-Oriented Programming (OOP) in C#, including encapsulation, inheritance, and polymorphism. It explains key concepts such as class properties, method overriding, abstract classes, sealed classes, and interfaces, along with examples demonstrating their usage. Additionally, it covers boxing and unboxing in C#, illustrating how value types can be converted to and from object types.

Uploaded by

omsaidesai9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views20 pages

UNIT 3 Notes - 2023-24 3rd Sem

This document discusses the pillars of Object-Oriented Programming (OOP) in C#, including encapsulation, inheritance, and polymorphism. It explains key concepts such as class properties, method overriding, abstract classes, sealed classes, and interfaces, along with examples demonstrating their usage. Additionally, it covers boxing and unboxing in C#, illustrating how value types can be converted to and from object types.

Uploaded by

omsaidesai9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT III PILLARS OF OOP

C# is a true object oriented programming language. Hence, classes form the bases for all the C#
programs. Anything that we want to represent in C# is encapsulated inside a class. The class is a
template of user defined type that contains instance variables, static members and methods that
operate upon them. An object is an instance of a class or can also be defined as a variable of type
class.

Important principles of object oriented programming

Encapsulation

It provides an ability to hide the internal details of an object from its users. The outside user may
not be able to change the state of an object directly. However the state of an object can be altered
using its methods. The class construct ensures encapsulation and the keywords private, public,
protected etc ensures data hiding.

Inheritance

This concept is used to build new classes from existing classes. The existing class is known as
base(super/parent) class and the new class is known as derived (sub/child) class. The concept of
inheritance facilitates reusability of existing code and improves the productivity of the
programmer.

Polymorphism

It is an important concept in object oriented programming. It refers to the ability to take more
than one forms.

Example : An operator or a method may exhibit different behaviour in different situations. The

behaviour depends on the type of data used in the operations.

Polymorphism can be implemented in two ways

1. Compile time polymorphism

a. Method overloading

b. operator overloading

2. Runtime polymorphism

a. Method overriding

C# Class Properties (get and set)

In C# private variables can only be accessed within the same class (an outside class has no
access to it). However, sometimes we need to access them and it can be done with properties.

A property is like a combination of a variable and a method, and it has two methods: a get and
a set method:
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
The general form of a property is shown below:

type name {

get{
//get method code
}

set{
//set method code
}
}

Example:
class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}

Example explained

 The Name property is associated with the name field. It is a good practice to use the same
name for both the property and the private field, but with an uppercase first letter.
 The get method returns the value of the variable name.
 The set method assigns a value to the name variable. The value keyword represents the
value we assign to the property.

Example Program

using System;

namespace Get_Set_Demo
{
class Student
{
private string name; // field
private int rollno; // field

public string Name // property


{
get { return name; }
set { name = value; }
}

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


public int RollNo // property
{
get{ return rollno; }
set{ rollno = value; }
}
}

class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.Name = "Aditya";
s.RollNo = 104;
Console.WriteLine("Student Name = "+s.Name);
Console.WriteLine("Student Roll Number = "+s.RollNo);
}
}
}

Inheritance

Reusability of code is an important feature of object oriented programming. C# classes can be


reused in several ways. Reusability is achieved by deriving new classes and using some of the
properties of the base class. The mechanism of deriving one class from another is known as
inheritance. Inheritance represents a kind of relationship between two or more classes.

For example, consider two classes A and B. We can create a class hierarchy such that B is
derived from A.

Defining a derived class


Derived class is completely new class that incorporates the data and methods of its base class. It
can also have its own data and methods.

Syntax
class derived_class_name : base_class_name
{
…………
}

In the above syntax, the : signifies that the properties of base class are extended to the derived
class. Classical inheritance may be implemented in several ways

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


Single inheritance
In this, there is one base class from which a new class is derived so the derived class inherits the
properties of base class.
class A
A {
base class ========
========
}
class B : A
{
==========
B derived class ==========
}

Multiple Inheritance
In this type, a class is derived from multiple base classes. In C# multiple inheritance is
implemented using interface.

• Cannot be implemented directly


• Implemented with interfaces

Multilevel inheritance
A common requirement in Object Oriented Programming is the use of derived class concepts and
use it extensively in building a class library or chain of classes. The derived class further can be
used as base class to derive another class, such an inheritance is called as multilevel inheritance.

class A
{
A super class ========
========
}
B Intermediate class B : A
class {
==========
==========
C sub class }
class C : B
{
=========
=========
}
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
Hierarchical inheritance
It is a way of transmitting features from a parent class to a base, child, or subclass in terms of
technical terms and the object-oriented aspect. The parent class or superclass is the class from
which the properties are taken, i.e. the features are inherited. Hierarchical inheritance describes
a situation in which a parent class is inherited by multiple subclasses. A type of inheritance in
which more than one class is inherited from a single parent or base class is known as
hierarchical inheritance.

B C D
//C# program to demonstrate Single Inheritance

using System;

namespace Demo_Inheritance

{
class Base
{
public void basePublic()
{
Console.WriteLine("Base Public");
}
protected void baseProtected()
{
Console.WriteLine("Base Protected");
}
private void basePrivate()
{
Console.WriteLine("Base Private");
}
}

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


class Derived : Base // single inheritance
{
public void printDerived()
{
Console.WriteLine("Print Derived");
baseProtected();
// basePrivate(); // Error
}
}

class Inheritance_1

public static void Main()

Derived d = new Derived();

Base b = new Base();

b.basePublic();

d.printDerived();

d.basePublic();

// d.baseProtected(); // Error

//d.basePrivate();

using System;

namespace Demo_Inheritance

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


class Animal

private int x;

protected int y;

public int z;

public void eat()

Console.WriteLine("Eating");

private void sleep()

Console.WriteLine("Sleeping");

protected void drink()

Console.WriteLine("Drinking");

class Dog : Animal

public void bark()

Console.WriteLine("Barking");

drink();

eat();

// x = 10; Error

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


y = 20;

z = 30;

class Inheritance_2

public static void Main(string[] args)

Dog d1 = new Dog();

Animal a = new Animal();

d1.eat();

d1.bark();

d1.z = 40;

//d1.x = 50; // Error

//d1.sleep(); // Error

// a.sleep(); // Error

// d1.drink(); // Error

Method Overriding
Inheritance enables to define methods repeatedly in super class and sub class. However,
sometimes it may be necessary to override a method used in superclass. In C#, method
overriding is implemented as follow:
Specify the method in the base class as virtual
Implement the method in the sub class using the keyword override

//Program to demonstarte method overriding


using System;

namespace Demo_Inheritance
{

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


class Bird
{
// Base class method as virtual
public virtual void moves() // hide this method
{
Console.WriteLine("Bird Moves");
}

public void eat()


{
Console.WriteLine("Bird Eats");
}
}
class Pigeon : Bird
{
// Derived class method as override
public override void moves()
{
Console.WriteLine("Pigeon Flys");
}

class OverrideDemo
{
public static void Main()
{
Pigeon p = new Pigeon();
p.moves(); // calls the moves() method of derived class

}
}
}

Method Hiding
Sometimes it may be necessary to derive from the classes provided by someone else. We may
also wish to re-define some of the methods present in such classes. For this, C# provides the
modifier new that hides a base class method and the new derived class method must be used
instead of the super class method.

//Program to demonstrate method hiding


using System;
class BaseClass
{
public void display() // Base class method
{
Console.WriteLine("Inside BaseClass method");
}
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
}
class DerivedClass : BaseClass
{
// Derived class method made as new method
// and not the inherited method
public new void display()
{
Console.WriteLine("Inside DerivedClass method");
}
}
class HidingMethodDemo
{
public static void Main()
{
DerivedClass obj = new DerivedClass();
// Calls the derived class method
obj.display();
}
}

Abstract Classes
 Sometime it is necessary to have one base class and a number of derived classes. The top
most class simply act as base for other classes and is not useful on its own. In such
situations we may never create the object of the base class. Such classes can be made as an
abstract classes.
 Abstract classes are implemented by using abstract modifier at the time of class definition.
 Abstract methods are implemented by using abstract modifier at the time of declaring a
method.
 Once the class is defined as abstract then the object of that class cannot be created. Hence, it
cannot be instantiated.
Ex:
abstract class Base
{
……
……
}
Class Derived : Base
{

……
……
}
Base b; // Error
Derived d; // No error

//C# program to demonstrate Abstract class and Abstract methods

using System;

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


// Defines an abstract class
abstract class Automobile
{
// Defines an abstract method
// method only needs to be declared and should be defined in the derived class
// abstract method should be overridden in the derived class
public abstract void Moves();

public void runs()


{
Console.WriteLine("Vehicle runs");
}
}
class bike : Automobile
{
// Defining the abstract method of base class by overriding it
// override modifier must be used

public override void Moves()


{
Console.WriteLine("Inside moves method");
Console.WriteLine("Bike moves");
}
}

class AbstarctClass
{
public static void Main()
{
bike b = new bike();
b.Moves(); // Overridden method will be called (derived class)
b.runs(); // Inheritted method will be called (base class)
// Attempting to create an object of abstract class results in error
// Automobile a = new Automobile(); //Error
}
}

Sealed Class (Non-Inheritable Classes)


A class whose properties and methods cannot be inherited is called as sealed class. In C#, the
modifier “sealed” is used to prevent a class from being inherited

Eg:
abstract class Base
{
……
……
}

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


Interfaces
C# does not support multiple inheritance directly. However, it provides an alternative approach
known as Interface. It supports the concept of multiple inheritance. An interface in C# is
reference type. It is defined by the keyword “interface”. It can contain one or more methods,
events, properties etc. But none of the interface members are implemented in it. Only signatures
are written inside the interface.

Following are important features of interfaces:


1. All the members of interface are implicitly public and abstract
2. An interface does not contain constant, read-only fields, constructors or destructors.
3. Interface members cannot be declared as static
4. Since the members are abstract, they does not include the implementation code
5. An interface can inherit multiple interfaces.

C# program to demonstrate multiple implementation of an interface


// one interface, two classes --> both the classes implements from the same interface
// Vehicle, Scooter, Car
using System;
interface IVehicle
{
void wheels(); // only declaration
}
interface IGearSystem
{
void gears(); // only declaration
}

class Scooter : IVehicle, IGearSystem


{
public void wheels() // Defined inside implemented class
{
Console.WriteLine("It’s a two wheeler");
}
public void gears()
{
Console.WriteLine("Automatic transmission");
}
}

class Car : IVehicle, IGearSystem


{
public void wheels() // Defined inside implemented class
{
Console.WriteLine("It’s a four wheeler");
}
public void gears()
{
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
Console.WriteLine("Manual transmission with 5 gears");
}
}
class InterfaceDemo
{
public static void Main()
{
Scooter activa = new Scooter();
activa.wheels();
activa.gears();

Car swift = new Car();


swift.wheels();
swift.gears();
}
}

C# program to demonstrate passing interface object as parameter


using System;
//Create an interface
interface IAnimal
{
void sound();
}

//Create a class and implement the interface


class Dog : IAnimal
{
public void sound()
{
Console.WriteLine("Bow Bow");
}
}

//Create another class and implement the interface


class Cat : IAnimal
{
public void sound()
{
Console.WriteLine("Mew Mew");
}
}

//Create a class and define a method to accept interface object as parameter

class ParameterClass
{
public static void ListenToMe(IAnimal Listener)
{
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
Listener.sound();
}
}

class InterfaceAsParameterDemo
{
public static void Main()
{
//Create an object of the interface but do not instantiate
IAnimal myAnimal;

//Create and instantiate object of Dog class


Dog myDog = new Dog();

//Instatiate object of Animal interface to Dog class


myAnimal = myDog as IAnimal;

//Invoke the method by passing object of Interface


ParameterClass.ListenToMe(myAnimal);

//Instatiate object of IAnimal interface to Cat class


myAnimal = new Cat();

//Invoke the method by passing object of Interface


ParameterClass.ListenToMe(myAnimal);
}
}

Boxing and Unboxing


In OOPs, the methods are invoked using objects. Since value types of int, float, long, etc are not
objects, we cannot use them to call methods. However, C# enables us to achieve this through
boxing and unboxing operations.
Boxing
Conversion of a value-type (int, char, etc) on stack to an object type on heap is known as boxing.
Ex:
int i = 100;
object obj = i; // boxing
This creates temporary reference type for object on the heap.
We can also use explicit type cast during boxing operation.
Ex:
int i = 100;
object obj = (object) i; // boxing
Here, the boxing operation creates copy of value i and assign it to obj. Now obj exist on the heap.

Unboxing
Conversion of an object type on heap to a value type on stack is known as unboxing.
Ex:
int i = 100;

object obj = i;
int j = (int)obj;
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
During unboxing operation, C# checks whether the value is already boxed and whether it is large
enough to hold the value of object, otherwise the operation may result in runtime error.

C# program to demonstrate boxing and unboxing


using System;
class Boxing_Unboxing_Demo
{
public static void Main()
{
int i = 100;
object obj = i; // boxing
Console.WriteLine("The value-type value = {0}", i);
Console.WriteLine("The object-type value = {0}", obj);
int j = (int)obj; // unboxing
Console.WriteLine("The value-type value = {0}", j);
}
}

Delegates in C#
Definition:
Delegates in C# are like pointers to functions. They hold the reference of a function and this
reference can be hanged at run time. Delegates are implicitly derived from System.Delegate
class.

A delegate can be declared using the delegate keyword before the function signature.
The syntax of a delegate is given as follows:

<access modifier> delegate <return type> <delegate name> (<parameters>)


Here the access modifier is followed by the keyword delegate. Then the return type is followed
by the delegate name and the required parameters.

How many ways we can call a method in C#?


In C#, we can call a method that is defined in a class in two ways. They are as follows:
 We can call the method using the object of the class if it is a non-static method or we can
call the method through class name if it is a static method.
 We can also call a method in C# by using delegates. Calling a C# method using delegate
will be faster in execution as compared to the first process i.e. either by using an object or
by using the class name.

Program on method called using object and class name .


namespace DelegateDemo
{
public class Program
{
//NonStatic method
public void Add(int x, int y)
{
Console.WriteLine(@"The Sum of {0} and {1}, is {2} ", x, y, (x + y));
}

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


//Static Method
public static string Greetings(string name)
{
return "Hello @" + name;
}

static void Main(string[] args)


{
Program obj = new Program();
//calling non static method through object
obj.Add(100, 100);
//Calling static method with class name
string GreetingsMessage = Program.Greetings("Nagaraj");
Console.WriteLine(GreetingsMessage);
Console.ReadKey();
}
}
}

How to invoke methods using delegates in C#?


If we want to invoke or call a method using delegates then we need to follow three simple steps.
The steps are as follows.
i. Defining a delegate
ii. Instantiating a delegate
iii. Invoking a delegate

Step1: Define a Delegate in C#


The syntax to declare a delegate in C# is very much similar to the function declaration. In
delegate, we need to use the keyword delegate. The syntax for defining a delegate:
<access modifier> delegate <return type> <delegate name> (arguments list);
Example: If you have a method like below.
public void Add(int x, int y)
{
Console.WriteLine(@"The Sum of {0} and {1}, is {2} ", x, y, (x + y));
}
Then we have to define a delegate like below.
public delegate void AddDelegate(int a, int b);

Step2: Instantiating the Delegate in C#.


Once we declare the delegate, then we need to consume the delegate. To consume the delegate,
first, we need to create an object of the delegate and while creating the object the method we
want to execute using the delegate should be passed as a parameter. The syntax to create an
instance of a delegate is given below.

DelegateName ObjectName = new DelegateName (target function-name);


Example:
AddDelegate ad = new AddDelegate(obj.Add);
While binding the method with delegate, if the method is non-static refer to it as the object of the
class and if it is static refer to it with the name of the class.

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


Step3: Invoking the Delegate in C#.
Once we create an instance of a delegate, then we need to call the delegate by providing the
required values to the parameters so that the methods get executed internally which is bound
with the delegates.
For example:
ad(100, 50);
ad.Invoke(200, 300);
At this point, the function that is referred to by the delegate will be called for execution.

Types of Delegates:
1. Single Cast Delegate(Same as previous contents)
2. Multicast Delegate

Multicast Delegate
 The delegate can point to multiple methods. A delegate that points multiple methods is
called a multicast delegate.
 It is used to hold the reference of multiple methods with a single delegate.
 By using "+" operator, we can add the multiple method references to the delegate object.
Same way, by using "-" operator we can remove the method references from the delegate
object.
 By using delegate we can pass methods as the parameter.

C# Events
An event is a delegate type class member that is used by the object or class to provide
notification to other objects that an event has occurred. The client object can act on an event by
adding an event handler to the event.

In this model, you have publishers who will do some logic and publish an "event." Publishers
will then send out their event only to subscribers who have subscribed to receive the specific
event.

In C#, any object can publish a set of events to which other applications can subscribe. The class
who raises events is called Publisher, and the class who receives the notification is
called Subscriber. There can be multiple subscribers of a single event

When the publishing class raises an event, all the subscribed applications are notified. The
following figure shows this mechanism.

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3


An event can be declared in two steps:

1. Declare a delegate.
2. Declare a variable of the delegate with event keyword.

Events are declared as follows:

<access modifier> event delegatename <event name> ;

Examples: public event EventHandler Click;

public event RateChange Rate;

In the above examples, EventHandler and RateChange are delegates and Click and Rate are
events.

Since events are based on delegates, we must first declare a delegate and then declare an instance
of the delegate using the keyword event.

/* Program to Demonstrate Event handler */


using System;
namespace Demo_Delegates
{
// delegate declaration first
public delegate void Edelegate(string str);
class Eventclass
{
//declaration of event
public event Edelegate Status;
public void TriggerEvent()
{
if (Status != null)
Status("Event Triggered");
}
}
class EventTest
{
public static void Main(string[] args)
{
Eventclass ec = new Eventclass();
EventTest et=new EventTest();
//EventClass is instantiated and it is subscribed to the
Status event
ec.Status += new Edelegate(et.EventCatch);

ec.TriggerEvent();
Console.ReadKey();
}
KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
public void EventCatch(string str)
{
Console.WriteLine(str);
}
}

Operator Overloading

C# operators can be defined to work with the user-defined data types such as structs and classes
in much the same way as the built-in types. For instance, C# permits us to add two class objects
with the same syntax that is applied to the basic types.

Example:

Vector u1,u2,u3;

------- // initialize u1 and u2 here

-------

u3=u1+u2; // adding two abjects, u1 and u2

where Vector is a class or a struct. Two vectors u1 and u2 are added (like a simple type) to give
a third vector u3. This means , C# has the ability to provide the operators with a special meaning
for a data type. This mechanism of giving such special meaning to an operator is known as
operator overloading.

Defining Operator Overloading


KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3
The general form of an operator method is

public static retval operator op(arglist)

Method body //task defined

operator is a keyword, followed by the operator op

The retval (return value) type is the type that we get when we use this operator.

The arglist is the list of arguments passed. The number of arguments will be one for the unary
operators and two for the binary operators.

KLS Gogte BCA – Belagavi SEM-III C# and .NET Framework –UNIT 3

You might also like