UNIT-3 Pillars of OOP Object Oriented Programming: Prof - Dharesh Kumatagi, Chetana Bca College, Vijayapur
UNIT-3 Pillars of OOP Object Oriented Programming: Prof - Dharesh Kumatagi, Chetana Bca College, Vijayapur
UNIT-3
Pillars of OOP
Object Oriented Programming
A programming model which is mainly organized around the objects is called Object
Oriented Programming or the Programming where the main focus of programmer while
modelling any problem is objects. (The name OOP indicates the same).
3 core principals of oops are
1. Encapsulation
2. Inheritance
3. Polymorphism.
Example:
Inheritance
Single Inheritance
Multi-level Inheritance
Multiple Inheritance
Single Inheritance
When a single derived class inherits properties from a single base class is called single
inheritance.
Class A
{
//data members;
//member functions;
}
Class B:A
{
//data members;
//member functions;
}
Example:
using System;
public class Employee
{
public float salary = 40000;
}
public class Programmer: Employee
{
public float bonus = 10000;
}
class TestInheritance{
public static void Main(string[] args)
{
Programmer p1 = new Programmer();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
Console.WriteLine (“Total Salary:”, p1.salary+p1.bonus);
}
}
Salary: 40000
Bonus: 10000
Total Salary:50000
Multi-level Inheritance
In multi-level inheritance, a derived class inherits from a base class and then the same
derived class becomes a base class for another derived class. The properties of one class
are inherited to different levels.
Class A
{
//data members;
//member functions;
}
Class B:A
{
//data members;
//member functions;
}
Class C:B
{
//data members;
//member functions;
}
In above syntax class B inherits properties of its parent class A. Class B is child class of
class A. Class C is child class of class B and it inherits all the properties of class B. Indirectly
class C is inheriting properties of class A through class B.
Example:
using System;
public class Employee
{
public float salary = 40000;
}
public class Programmer: Employee
{
public float bonus = 10000;
}
public class SeniorProgrammer: Programmer
{
public float extrabonus = 500;
}
class TestInheritance{
public static void Main(string[] args)
{
SeniorProgrammer p1 = new SeniorProgrammer ();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
Console.WriteLine("ExtraBonus: " + p1.extrabonus);
Console.WriteLine (“Total Salary:”, p1.salary+p1.bonus+p1.extrabonus);
}
}
Salary: 40000
Bonus: 10000
ExtraBonus: 500
Total Salary:50500
Multiple inheritance
Multiple inheritance
In multiple inheritance, a single derived class inherits from multiple base classes. C#
doesn't support multiple inheritance. However, we can achieve multiple inheritance
through interfaces.
interface A
{
//data members;
//member functions;
}
interface B
{
//data members;
//member functions;
}
Class C:A,B
{
//data members;
//member functions;
}
using System;
namespace MathOperations
{
interface calc1
{
int add(int a, int b);
}
interface calc2
{
int sub(int x, int y);
}
class Calculation : calc1, calc2
{
public int result1;
public int add(int a, int b)
{
return result1 = a + b;
}
public int result2;
public int sub(int x, int y)
{
return result2 = x - y;
}
class Program
{
static void Main(string[] args)
{
Calculation c = new Calculation();
c.add(8, 2);
c.sub(20, 10);
Console.WriteLine("Multiple Inheritance concept Using Interfaces :\n ");
Console.WriteLine("Addition: " + c.result1);
Console.WriteLine("Substraction: " + c.result2);
Console.ReadKey();
}
}
}
}
Polymorphism
Polymorphism is a Greek word, meaning "one name many forms". In other words,
one object has many forms or has one name with multiple functionalities. "Poly" means
many and "morph" means forms. Polymorphism provides the ability to a class to have
multiple implementations with the same name. Static Polymorphism:
The same entity (method or operator or object) can perform different operations in
different scenarios. It provides the ability for a class to have multiple implementations with
the same name.
Method calls are defined at the time of compilation. Static/Compile time polymorphism can
be implemented using method overloading.
Method overloading allows us to have multiple methods with the same name having
different datatypes of parameter, or a different number of parameters, or both.
Example:
using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}
void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args)
{
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C#");
Console.ReadKey();
}
}
}
Printing int: 5
Printing float: 500.263
Printing string: Hello C#
Dynamic/Runtime polymorphism
During inheritance in C#, if the same method is present in both the superclass and
the subclass. Then, the method in the subclass overrides the same method in the
superclass. This is called method overriding.
C# allows you to create abstract classes that are used to provide partial class
implementation of an interface. Implementation is completed when a derived class inherits
from it. Abstract classes contain abstract methods, which are implemented by the derived
class.
Derived class inherits the methods of parent class with override keyword.
Example:
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Program
{
static void Main(string[] args)
{
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
➢ To achieve security - hide certain details and only show the important details of an
object (interface).
➢ C# does not support "multiple inheritance" (a class can only inherit from one base
class). However, it can be achieved with interfaces, because the class can implement
multiple interfaces.
➢ An interface can be used when you want the derived classes to fully implement all of
the methods introduced in the base class.
➢ Abstraction can be achieved via interfaces.
➢ Interface Allows you to decouple a method’s definition from its inheritance hierarchy.
➢ An interface can be used to achieve polymorphic behavior, a single method of an
Interface can have multiple redefinitions into multiple classes of unrelated types. Here,
every derived class is free to provide its own implementation.
➢ Interfaces are best suited to achieve Dispose Pattern by defining an IDisposable
interface.
➢ An Interface doesn’t contain a constructor, which helps to prevent extra roundtrip
when creating an object of the derived class through the reference pointer of the
interface.
Implementing an Interface in C#
Interfaces are used as super classes whose properties are inherited by other classes. It is
necessary to create a class that implements interfaces as follows.
Example:
using System;
interface Addition //declaring an interface
{
Int Add();
}
Class Computation : Addition // Extending an interface
{
int x,y;
public Computation(int x, int y) // Constructor
{
this.x=x;
this.y=y;
}
Public int Add() // implementing Add
{
return (x+y);
}
}
Class interfcaeTest
{
public static void Main()
{
Computation c=new Computation(200,100);
Addition a=(Addition) c; //casting
Console.WriteLine(“Sum=” + a.Add());
}
}
using System;
interface Addition
{
int Add ( );
}
interface Multiplication
{
int Mul ( );
}
class Computation : Addition, Multiplication
{
int x, y;
public Computation (int x, int y ) / /Constructor
this.x = x;
this.y = y;
public int Add ( ) / /Implement Add ( )
{
return ( x + y );
}
public int Mul ( )
{ / /Implement Mul ( )
return ( x * y );
}
}
class Interface Test1
{
public static void Main( )
{
Computation com = new Computation (10,20);
Addition add = (Addition ) com; / / casting
Console. WriteLine ("Sum = " + add.Add ( ));
Multiplication mul = (Multiplication) com; / / casting
Console. WriteLine("Product = " + mul.Mul ( ) );
}
}
using System;
interface Area
{
double Compute ( double x );
}
class Square : Area
{
public double Compute (double x)
{
return (x * x)
}
}
class Circle : Area
{
public double Compute (double x)
{
return (Math.PI * x * x);
}
}
class Interface Test2
{
public static void Main( )
{
Square sqr = new Square ( );
Circle cir = new Circle ( );
Area area; / /casting
area = sqr as Area; / /casting
Console. WriteLine ("Area of Square ="+ area. Compute(10.0));
area = cir as Area;
Console. WriteLine ("Area of Circle="+ area. Compute(10.0));
}
}
Explicit interface declarations mean that the interface members are not available
on types other than the interface itself, so implementing types would need to be cast to
the interface before accessing them publicly.
The main reason for explicit interface definitions is to avoid naming conflicts if you
happen to implement two interfaces that contain methods with the same signature... the
explicit definition allows the compiler to keep the signatures distinct enough to resolve.
}
}
class interfaceTest
{
static void Main(string[] args)
{
I1 i1 = new C();
I2 i2 = new C();
i1.printMethod(); // call to method of I1
i2.printMethod(); // call to method of I2
}
}
When we inherit class into another class then object of base class is initialized first. If
a class do not have any constructor, then default constructor will be called. But if we have
created any parameterized constructor then we must initialize base class constructor from
derived class.
We must call constructor from another constructor. When we have to call base class
constructor from derived class then we use base keyword.
When we create the object of ClassA class then first it will call ClassB class constructor
but ClassB class constructor first initialize the base class constructor then ClassB constructor
will be initialized. It is very important point to note down the base class constructor initialized
first.
Example:
public class ClassA
{
public int p, q;
public ClassA(int p1, int p2)
{
p = p1;
q = p2;
}
public int sum()
{
return (p + q);
}
}
//derived class/ child class
public class ClassB : ClassA
{
public int r;
#output
Sum of 2 numbers:7
Sum of 3 numbers:9
Method overriding
In c#, Method Overriding means override a base class method in the derived class
by creating a method with the same name and signatures to perform a different task. The
Method Overriding in c# can be achieved using override & virtual keywords and the
inheritance principle.
If we want to change the behavior of the base class method in a derived class, then
we need to use method overriding. The base class method we want to override in the
derived class needs to be defined with a virtual keyword. We need to use the override
keyword in the derived class while defining the method with the same name and
parameters then only we can override the base class method in a derived class.
In c#, the Method Overriding is also called run time polymorphism or late binding.
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
using System;
namespace PolymorphismDemo
{
class Class1
{
//Virtual Function (Overridable Method)
public virtual void Show()
{
//Parent Class Logic Same for All Child Classes
Console.WriteLine("Parent Class Show Method");
}
}
class Program
{
static void Main(string[] args)
{
Class1 obj1 = new Class2();
obj1.Show();
#output
Parent Class Show Method
Child Class Show Method
Parent Class Show Method
Child Class Show Method
A sealed class, in C#, is a class that cannot be inherited by any class but can be
instantiated.
The design intent of a sealed class is to indicate that the class is specialized and there is
no need to extend it to provide any additional functionality through inheritance to override
its behaviour.
The following are the important points which we need to remember about the sealed
keyword in the c# programming language.
➢ In c#, to apply a sealed keyword on a method or property, it must always use with
override.
➢ In c#, we should not use an abstract modifier with a sealed class because an
abstract class must be inherited by a class that provides an implementation of the
abstract methods or properties.
➢ In c#, the local variables cannot be sealed.
➢ In c#, structs are implicitly sealed; they cannot be inherited.
Example:
using System;
namespace SealedClass {
sealed class Animal {
}
#output
error CS0509: 'Dog': cannot derive from sealed type 'Animal'
Boxing and unboxing in C# allow developers to convert .NET data types from value type
to reference type and vice versa.
Boxing: Converting a value type to a reference type is called called boxing in C#. A boxing
conversion permits any value-type to be implicitly converted to the type object or to any
interface-type implemented by the value-type.
Reference types store on heap where it contains the address of the value and value
type is just an actual value stored on the stack.
Now, as shown in the first example, int i is assigned to object o. Object o must be
an address and not a value itself. So, the CLR boxes the value type by creating a new
System.Object on the heap and wraps the value of i in it and then assigns an address of
that object to o. So, because the CLR creates a box on the heap that stores the value, the
whole process is called 'Boxing'.
int i = 10;
object o = i; //performs boxing
Example:
using System;
class Program
{
static void Main(string[] args)
{
int num1 = 42;
object obj1 = num1;
System.ConsoleWriteLine("Value is : {0}", num1);
// Value is : 42
System.ConsoleWriteLine("Object is : {0}", obj1);
// Object is : 42
}
}
#output
Value is:42
Object is:42
In the example above, the num1 variable is the value, and we boxed it into a reference
called obj1. The obj1 reference is of type object, which is the base reference type in .NET.
Unboxing
Unboxing is the reverse of boxing. It is the process of converting a reference type to value
type. Unboxing extract the value from the reference type and assign it to a value type.
object o = 10;
int i = (int)o; //performs unboxing
using System;
class Program
{
static void Main(string[] args)
{
int num1 = 42;
object obj1 = num1;
num1 = 10_000;
int num2 = (int)obj1;
System.ConsoleWriteLine("Value is : {0}", num1);
// Value is : 10000
System.ConsoleWriteLine("Object is : {0}", obj1);
// Object is : 42
System.ConsoleWriteLine("Value2 is : {0}", num2);
// Value is : 42
}
#output
Value is : 10000
Object is : 42
Value2 is : 42
Delegates
The general meaning of the delegate is “a person is acting for another person”. In C# a method
can act for another method.
Delegate in c# is a class type object and it is used to invoke a method that has been
encapsulated into it at the time its creation.
A delegate declaration defines a class using System. Delegate base class. Delegates are any
function whose signature matches the delegate signature exactly.
The delegate instance holds the reference to delegate methods. Instance is used to invoke
the methods. Indirectly.
➢ Delegates are similar to C++ function pointers, but are type safe.
➢ Delegate gives a name to a method signature.
➢ Delegates allow methods to be passed as parameters.
➢ Delegates can be used to define callback methods.
➢ Delegates can be chained together; for example, multiple methods can be called on
a single event.
➢ Delegate helps in code optimization.
Delegate Declaration
Syntax:
//class body;
Access modifiers can be public, private, protected and internal. Delegate is keyword used declare a
delegate type. Return-type indicates return type of delegate. Parameter-list identifies the signature
of a delegate. Delegate-name is any valid identifier given by the user.
Example:
using System;
//declaration of delegate
public delegate int Maths (int x, int y)
class Cal
{
//delegate method definition
public static int Add(int a, int b)
{
return (a+b);
}
public static int Mul(int a, int b)
{
return (a*b);
}
}
class delegateTest
{
Public static void Main()
{
//delegate instances
Maths m1=new Maths(Cal.Add);
Maths m2=new Maths(Cal.Mul);
//invoking delegates
int m=m1(20,10);
int n=m2(20,10);
Console.WriteLine(“m=”+m);
Console.WriteLine(“n=”+n);
}
}
Types of delegates
1. Single cast delegate
2. Multi cast delegate
A single cast delegate holds the reference of only single method. It is derived from
System.Delegate class.
Example:
using System;
//declaration of delegate
public delegate int Maths (int x, int y)
class Cal
{
//delegate method definition
public static int Add(int a, int b)
{
return (a+b);
}
public static int Mul(int a, int b)
{
return (a*b);
}
}
class delegateTest
{
Public static void Main()
{
//delegate instances
Maths m1=new Maths(Cal.Add);
Maths m2=new Maths(Cal.Mul);
//invoking delegates
int m=m1(20,10);
int n=m2(20,10);
Console.WriteLine(“m=”+m);
Console.WriteLine(“n=”+n);
}
}
A delegate which holds the reference of more than one method is called multi-cast delegate.
A multicast delegate only contains the reference of methods which return type is void. The +
and += operators are used to combine delegate instances. Multicast delegates are considered
equal if they reference the same methods in the same order.
It is derived from System.MulticastDelegate class.
Example:
using System;
delegate void City();
class MDelegate
{
#Output
New Delhi
New York
New York
New Delhi
New Delhi
Events
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence
such as system generated notifications. Applications need to respond to events when they
occur.
The event is an encapsulated delegate. C# and .NET both support the events with the
delegates. When the state of the application changes, events and delegates give the
notification to the client application. Delegates and Events both are tightly coupled for
dispatching the events, and event handling require the implementation of the delegates.
A publisher is an object that contains the definition of the event and the delegate.
A subscriber is an object that accepts the event and provides an event handler.
using System;
namespace Example
{
public delegate string demoDelegate(string str);
class MyEvents
{
event demoDelegate myEvent;
public MyEvents()
{
this.myEvent += new demoDelegate(this.Display);
}
public string Display(string name)
{
return (name);
}
static void Main(string[] args) {
MyEvents e = new MyEvents();
string res = e.myEvent("Jack");
Console.WriteLine("RESULT...\n"+res);
}
}
}
#output
RESULT...
Student: Jack
Subject: Science
Operator Overloading
Here,
1. The return type is the return type of the function.
2. the operator is a keyword.
3. Op is the symbol of the operator that we want to overload. Like: +, <, -, ++, etc.
4. The type must be a class or struct. It can also have more parameters.
5. It should be a static function.
We can overload all the binary operators i.e +, -, *, /, %, &, |, <<, >>.
We can overload all the unary operators i.e. ++, –, true, false, + , -, ~.
Some operators like &&, ||,[] ,() cannot be overloaded.
We can overload relational operators in pairs. These are ==, =, <, >, <= , >= etc.
We can overload compound operators as they are already overloaded with respect to the
binary operator.
{
return new Complex(n1.real + n2.real, n1.imag + n2.imag);
}
// Override the ToString method to display an complex number in the suitable format:
public override string ToString()
{
return (String.Format("{0} + {1}i", real, imag));
}
public static void Main()
{
Complex cnum1 = new Complex(4, 5);
Complex cnum2 = new Complex(5, 6);
// Add two Complex objects (num1 and num2) through the
Complex addition = cnum1 + cnum2;
// Print the numbers
Console.WriteLine("First complex number: {0}", cnum1);
Console.WriteLine("Second complex number: {0}", cnum2);
Console.WriteLine(“The sum of the two numbers: {0}", addition);
// Hault the output screen
Console.Read();
}
}
#Output
First Complex Number : 4+5i
Second Complex Number : 5+6i
The sum of the two numbers: 9 + 11i
08. An abstract class can contain fields and An interface cannot have fields.
constants.
09. If multiple implementations of methods If multiple unrelated classes only share
are of the same kind and use common method signatures and have different
behavior, then it’s better to use an implementations of methods, then it is
abstract class. So that the common better to use Interface.
implementation code does not need to
be repeated in each of the descending
or subclasses.
10. An abstract class can contain the main An interface can’t contain the main method.
method in C#.
C# Abstract Class
We can use an abstract class as a base class and all derived classes must implement
abstract definitions. An abstract method must be implemented in all non-abstract classes
using the override keyword. After overriding the abstract method is in the non-Abstract
class. We can derive this class in another class and again we can override the same
abstract method with it.
Example:
using System;
namespace AbstractClass
{
abstract class Animal
{
public abstract void makeSound(); // abstract method
}
class Dog : Animal // inheriting from abstract class
{
// provide implementation of abstract method
public override void makeSound()
{
Console.WriteLine("Bark Bark");
}
}
class Program
{
static void Main (string [] args) {
Dog obj = new Dog(); // create an object of Dog class
obj.makeSound();
Console.ReadLine();
}
}
}
#output
Bark Bark