
Hello Everyone, As we seen the basic fundamentals C# programming in our First blog . So the Next point of C# programming will be about OOPs (Object Oriented Programming). OOPs refers to languages that uses objects in programming. Object-oriented programming aims to implement real world entities like inheritance,hiding, polymorphism etc in programming.
OOPs in C# :
OOP stands for Object-Oriented Programming.
There are four pillars which describes the OOPs concepts.
Pillars of OOPS in C#. So first we have to understand what OOPS is, and how it differs from procedural programming. in procedural programming. In Procedural programming. We are applying methods and procedures to data while OOP is about creating objects that can contain data as well as methods.
Procedural programming is bases on an unreal world. Obejct-oriented programming is bases on the real world. Like at starting of our coding life we learn logic building through procedural programming like C Language while for real world implementation we are using OOP like C#, Java,etc.
There are four pillars :
1. Inheritance :
Simply we can say it is a mechanism in which a child object acquires all property of the parent object. As a real-life example, we can say we are the child class and we will access all properties of our parents this is in Inheritance. As given figure you can understand Inheritance.
There are Four types of inheritance,
1. Single inheritance : When one class inherits another class at the time we can say it is single inheritance.
In the above image, we can see A is parents class and B is child class so as per defination you can comapre this example like B is accessing the property of its parents class and that ia A.
Lets see the coding example of the inherited field as well as method,
using System;
public class Animal
{
public void eat() { Console.WriteLine("Eating..."); }
}
public class Dog: Animal
{
public void bark() { Console. WriteLine("Barking..."); }
}
class TestInheritance2{
public static void Main(string[] args)
{
Dog di = new Dog();
di.eat();
di.bark();
Output:
Eating...
Barking...
As given example, you can see we have one parent class(Animal) with one public method eat and one child class(Dog) with public method bark. So when we try to access through the object of child(Dog) class first it will print data from parents method eat and at the last, it will print the child method bark.
2. Multi-level Inheritance : When one class inherits another and it also inherits by another at the time we can say it is Multilevel inheritance.
In the above figure, you can see that C is accessing the property of B and B is also accessing the property of A. As a real-life example, we can sat the grandchild is accessing the property of its parent class and the parent is accessing the property of its parents so we can say it is an example of Multilevel inheritance.Lets see one Example of Multilevel inheritance.
using System;
public class Animal
{
public void eat() { Console.WriteLine("Eating..."); }
}
public class Dog: Animal
{
public void bark() { Console. WriteLine("Barking..."); }
}
public class BabyDog : Dog
{
public void weep() { Console.WriteLine("Weeping..."); }
}
class TestInheritance2
{
public static void Main(string[] args)
{
BabyDog d1 = new BabyDog();
d1.eat();
d1.bark();
d1.weep();
}
}
Output :
Eating...
Barking...
Weeping...
As per given example, we can see BabyDog is accessing the property of its parent class means Dog, and Dog is also accessing the property of its parent class means Animal. So when we try to access the class through making grandchild(BabyDog) object first it will print public method of grandparents(eat) the it will print public method of itself(weep).
3. Multiple inheritance : When one subclass or child class is accessing the property of its multiple parent or superclass at that time we can say it is multiple inheritance.
In the above figure, you can see C is a child class or subclass and that is the accessing property of its parent class or superclass. As a real-life example, we can say we are accessing the property of our mom and dad means a single child accessing property of multiple classes. so it ts an example of multilevel inheritance.
using System;
namespace MyApplication
{
interface IFirstInterface
{
void myMethod(); // interface method
}
interface ISecondInterface
{
void myOtherMethod(); // interface method
}
// Implement multiple interfaces
class DemoClass : IFirstInterface, ISecondInterface
{
public void myMethod()
{
Console.WriteLine("Some text..");
}
public void myOtherMethod()
{
Console.WriteLine("Some other text...");
}
}
class Program
{
static void Main(string[] args)
{
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
}
Output :
4.Hierarchical inheritance : 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.
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. The base class shares many of the same properties as the parent class, especially those that are common in the parent class. A single base class gives rise to many classes. It’s like having several children, each with their own set of characteristics acquired from their parents.
For example, In the figure above, class A acts as the base class(parent class) for the child classes B, C, and D.Lets take one example of hierarchical inheritance.
using System; namespace type_inheritance { class BaseClass { public void Show1() { Console.WriteLine("this is a base class.."); } } class DerivedClass1 : BaseClass { public void Show2() { Console.WriteLine("this is the 1st derived class.."); } } class DerivedClass2 : BaseClass { public void Show3() { Console.WriteLine("this is the 2nd derived class.."); } } class program { public static void Main(string[] args) { DerivedClass1 dc1 = new DerivedClass1(); dc1.Show1(); dc1.Show2(); Console.ReadLine(); } } } Output : this is a base class.. this is the 1st derived class..
2. Encapsulation :
Simply we can say Encapsulation is a process of binding data members and data function together. or un another sense, we can say it is a process of binding variables, properties, and method together.
Let's understand encapsulation with a real life simple example like capsule is one of the examples of encapsulation. Like in Capsule it binds all chemical contents required for curing specific disease together just like the class which binds data members and member functions.Let's understand through one coding example what will happen if we did not use encapsulation or we can say how it will help us to hide data.
Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers −
Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.
The following example illustrates this −
using System; namespace RectangleApplication { class Rectangle { //member variables public double length; public double width; public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.length = 4.5; r.width = 3.5; r.Display(); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following result −
Length: 4.5 Width: 3.5 Area: 15.75
In the preceding example, the member variables length and width are declared public, so they can be accessed from the function Main() using an instance of the Rectangle class, named r.
The member function Display() and GetArea() can also access these variables directly without using any instance of the class.
The member functions Display() is also declared public, so it can also be accessed from Main() using an instance of the Rectangle class, named r.
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
The following example illustrates this −
using System; namespace RectangleApplication { class Rectangle { //member variables private double length; private double width; public void Acceptdetails() { Console.WriteLine("Enter Length: "); length = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter Width: "); width = Convert.ToDouble(Console.ReadLine()); } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following result −
Enter Length: 4.4 Enter Width: 3.3 Length: 4.4 Width: 3.3 Area: 14.52
In the preceding example, the member variables length and width are declared private, so they cannot be accessed from the function Main(). The member functions AcceptDetails() and Display() can access these variables. Since the member functions AcceptDetails() and Display() are declared public, they can be accessed from Main() using an instance of the Rectangle class, named r.
Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance. We will discuss this in more details in the inheritance chapter.
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
The following program illustrates this −
using System; namespace RectangleApplication { class Rectangle { //member variables internal double length; internal double width; double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.length = 4.5; r.width = 3.5; r.Display(); Console.ReadLine(); } } }
When the above code is compiled and executed, it produces the following result −
Length: 4.5 Width: 3.5 Area: 15.75
In the preceding example, notice that the member function GetArea() is not declared with any access specifier. Then what would be the default access specifier of a class member if we don't mention any? It is private.
The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.
3. Abstraction :
Simply abstraction is a process of hiding unnecessary things from users or we can say just show the necessary things. In a proper definition manner, we can say Abstraction is the process of showing only essential/necessary features of an entity/ object to the outside world and hide the other irrelevant information.
Essential things for Car users :
Irrelevant things for Car users :
In the above figures, you can see whenever car user purchase a car they think about the pain of car, the comfort of the car, gearbox system like automatic or manual but ca user never think like how will be the exhaust system will work, how the engine will generate torque, etc. so we can say this is some unessential thing for car user so car manufacturer will hide this unnecessary thing from car user and will just show the essential thing like paint, comfort, etc.
Using abstract keywords we can hide unessential data from the user. We can use the Abstract Method and Abstract Class.
The abstract class is restricted means no one can access the abstract class by making an object. if we want to use first we have to inherit that class from another class and by making an object of the child we can access abstract class.
The abstract method we can use in only an abstract class. An abstract method hasn't body. When we write an abstract method under the abstract class we are just writing the signature of that class. We can write its body in the inherited class.
Let's understand through coding example,
// Abstract class abstract class Animal { // Abstract method (does not have a body) public abstract void animalSound(); // Regular method public void sleep() { Console.WriteLine("Zz2"); } } // Derived class (inherit from Animal) class Pig : Animal { public override void animalSound() { // The body of animalSound() is provided here Console.WriteLine("The pig says: wee wee"); } } class Program { static void Main(string[] args) { Pig myPig = new Pig(); // Create a Pig object myPig-animalSound(); // Call the abstract method myPig-sleep(); // Call the regular method } } Output : The pig says : wee wee Zzz
Now in above figure , you can see to access the abstract class we inherit it from another class and it is a pig. so now we can access it and also you can see we have written the signature only of the abstract method under the abstract class. so the main body of that class is written in the inherited class that you can see. So at the end when we class both the regular method and the abstract method by making an object first it will print the abstract method and then it will print the regular method.
4. Polymorphism :
Polymorphism was derived from two greek words Poly and Morph.Poly means Many and Morph means Forms. So we can say polymorphism means having many forms. It provides the ability for a class to have multiple implementations with the same name.Polymorphism has two types,
1. Method OverLoading or Compile Time Polymorphism
2. Method OverRiding or Run Time Polymorphism
public class TestData { public int Add(int a, int b, int c) { return a + b +c; } public int Add(int a, int b) { return a + b; } } class Program { static void Main(string[] args) { TestData dataClass = new TestData(); int add2 = dataClass.Add(45, 34, 67); int addi = dataClass.Add(23, 34); } }
This is an example of method overloading where the method's name is the same but has different parameters. Like in above example, you can see TestData class have two methods and both methods name are the same Add but having different parameters like in the first method we are passing int a,b and c while in second method we are passing int a and b so this the method overloading so it will overload another method as per the passing parameters like if user gives 3 integers value it will overload method having two parameters and print answer.
class base_class
{
public void e2e();
}
class derived_class : base_class
{
public void e2e();
}
class Main_Method
{
static void Main()
{
derived_class d = new derived_class();
d.e2e();
}
}
This is an example of method overriding so it means the method name will be the same, passing parameters will be also the same but the class will be different. like in this example you can see we have two methods with the same name and same parameters (e2e()) but having different classes. one is parent class and the second is child class. so this is an example of overriding.
Conclusion
So in this blog, i have try to explain all four pillars of OOPS in C# with as much as the simplest and realistic example so you can understand more. Now i think you can differentiate all four pillars with real-life examples as well as Coding examples.