What is
OOP?
OOP (Object
Oriented Programming) is a programming technique in which programs are
written on the bases of the object.
Object: Object
is an encapsulation of fields and related behaviors of a particular type
(class).
Pillars of
Object Oriented Programming
There are
mainly 4 pillars of OOP.
A)Inheritance,
B)Polymorphism, C)Encapsulation, D)Abstraction.
Detail of
each topic is given below;
A)Inheritance: Inheritance
is an important concept of OOP in which one (child) class inherited all the
members of the other (base, parent) class and may have also its own, e.g.
Vehicle and Car relation, is a relationship defines the inheritance like
car is a vehicle. Major benefit of inheritance is reuse.
Inheritance
Modifiers for Classes
→Abstract: Cannot
make the instances/Object of this class.
→Sealed:
Cannot inherited, only make the object of this class.
→Static:
Cannot inherit as well as cannot make the object.
→Concrete
Class/Normal
Class:
Inherited as well as make object of this
type
of class. Classes that implement the abstract class.
B)Polymorphism: Polymorphism
means many forms. For example one method of parent class with same name is use
in different child or inherited classes with
different functionality with slightly changing in method. Main two
types of polymorphism as given under:
i). Overriding:
Providing a
different implementation for functionality of an inherited method
is called method overriding.
Following
are some basic rules for method overriding in .NET
♦Method
must be inherited.
♦Signature
(Name + Parameters of a method (type, kind (out, ref))) prams parameter is not
included, return type and access modifier of inherited method and overridden
method must be same/match.
♦Inherited
method must be declared with the virtual or abstract keyword.
♦Override
method must be declared with the override keyword.
ii).Overloading:
Overloading
means that same name of method used with different parameters, sequence of
parameters, number of parameters, types of parameters.
In C#, polymorphism can be implemented in two ways: static (compile-time) polymorphism and dynamic (runtime) polymorphism.
- Static Polymorphism: Achieved through method overloading and operator overloading. It allows multiple methods or operators with the same name but different parameters to coexist, with the specific method or operator being invoked determined at compile time based on the arguments passed.
- Dynamic Polymorphism: Achieved through method overriding. It allows a method in a derived class to have the same name and signature as a method in its base class, but with different implementation details. The method that gets executed is determined at runtime, depending on the type of the object.
C)Encapsulation: Packing in
one unit like capsule of a medicine. Remember Encapsulation is not a Data
Hiding but leads to Data Hiding. Example include the object of the particular
class can only use the data members of the class, any other object of different
class cannot use it directly.
D) Abstraction: Hide the
detail from the user, e.g. the console class having multiple methods. The user
use it only and not seen the code of the console class. Private Fields is an
example of abstraction. Real life object have many type of data members,
Capture only relevant details that are relevant to current perspective. In
interview, the interviewer only focusing your abilities that he or she
needed indeed. Abstraction can be very useful in Analysis and Design.
Information hiding/ Data Hiding
There are two type of abstraction.
i).Data Abstraction
We take an example of Receipt.
Show the Full Name = Ghazanfar Ali
Ghazi.
How we get the Full Name?
We got it from firstName, MiddleName,
LastName properties.
Same with Full Address = Country,
City, StreetAddress
Also we add additional check on
country and City to insert
only characters.
ii).Function Abstraction
1.Import Data 2.Validate Data
3.Insert Data.
But the user have no concern about
this. It is called Abstraction.
Following examples are explain all these four concepts in detail;
A)
Examples:
1. Inheritance of Normal class
using System;
namespace Practice_2
{
public class Human
{
public string Name;
public string Address;
public int Age;
}
}
using System;
namespace Practice_2
{
public class Teacher : Human
{
public string EducationExperience;
public string SchoolName;
}
}
using System;
namespace Practice_2
{
public class Doctor: Human
{
public string WorkingExperience;
public string HospitalName;
}
}
using System;
namespace Practice_2
{
class APP2_Program
{
static void Main(string[] args)
{
//Here we can get all
members of Teacher class as well as Human class members.
Teacher objTeacher = new Teacher();
}
}
}
Here we see that child classes Teacher and Doctor are
inheriting the base class Human. In our main Program,
we make an object of one of the child class like Teacher class, it access its
members as well as its base/parent class Human's members also.
2.
Inheritance of Abstract class
using System;
namespace Practice_2
{
public abstract class MyAbstractClass
{
//Error:
Virtual or Abstract member can not be private
//abstract
void MyAbsratcMethod()
//{
//
Console.WriteLine("");
//
Console.Write("This is test method");
//
Console.WriteLine("");
//}
int a = 5;
//Error:
Can not declare a body because it is marked as abstract
//public
abstract void MyAbsratcMethod()
//{
//
//}
int b;
//The class
that want to inhert MyAbstractClass, must Overide its abstract memebers.
//Signature
(Mehotd Name + Parmaters of a method (type, kind(out, ref)), params parameter
is not included,
//Return
type and access modifiers of an inherited mehtod and overriden method must
match/same.
//Inherited
method must be decalre with the abstract keyword.
//Override
method must be declare with the override keyword.
public abstract void MyAbstractMethod();
internal abstract int MyAbstractMethod(string a, int b);
//Error:
Virtual or Abstract member can not be private
//virtual
int MyVirtaulMethod()
//{
//
return 1;
//}
int c;
//The class
that want to inhert MyAbstractClass, have an option to Overide its virtaul
memebers
//Signature
(Mehotd Name + Parmaters of a method (type, kind(out, ref)), params parameter
is not included,
//Return
type and access modifiers of an inherited mehtod and overriden method must
match/same.
//Inherited
method must be decalre with the virtaul keyword.
//Override
method must be declare with the override keyword.
public virtual int MyVirtaulMethod()
{
return 1;
}
}
}
As we inherit Abstract class 'MyAbstract' we see a
small sign under our Abstract class name. Press 'ctrl+.' and we
have a message saying (Implement abstract class 'MyAbstractClass') as showing
in the following snapshot;
Click on this message and in our child class we have all of our abstract members implemented, as showing in the following piece of code;
using System;
using System.Threading.Tasks;
namespace Practice_2
{
public class SampleClass : MyAbstractClass
{
//Here we override the base class method MyAbstractMethod() and provide different functionality in our child class SampleClass
public override void MyAbstractMethod()
{
//Here we add actual functionality for this method...
}
//Here we override the
base class method MyAbstractMethod(string a, int b) and provide different
functionality in our child class SampleClass
//And also over load the
method of base class 'MyAbstractClass with same name but with different
paramaters in our child class SampleClass
internal override int MyAbstractMethod(string a, int b)
{
//Here we add actual functionality for this method...
}
}
}
3. Types of classes with examples
Abstract: Cannot
make the instances/Object of this class.
using System;
public abstract class MyAbstractClass
{
}
using System.Text;
namespace Practice_2
{
public class APP2_Program
{
static void Main(string[] args)
{
//Error: Cannot create an instance of the abstract class or interface
MyAbstractClass obj =new MyAbstractClass();
}
}
}
Sealed: Cannot inherited, only make the object
of this class.
using System;
public sealed class MySealedClass
{
}
using System;
//Error : 'Practice_2.MyDemoClass': cannot derive
from sealed type 'Practice_2.MySealedClass'
public class MyDemoClass : MySealedClass
{
}
Static: Cannot inherit as well as cannot
make the object.
using System.Text;
namespace Practice_2
{
public class APP2_Program
{
static void Main(string[] args)
{
//Error 1 Cannot declare a variable of static type
'Practice_2.MyStaticClass'.
//Error 2 Cannot
create an instance of the static class 'Practice_2.MyStaticClass'
MyStaticClass objMyStaticClass = new MyStaticClass();
}
}
}
public static class MyStaticClass
{
}
Concrete
Class/Normal
Class:
Inherited as well as make object of this
type
of class. Classes that implement the abstract class.
using System.Text;
namespace Practice_2
{
public class APP2_Program
{
static void Main(string[] args)
{
Human objHuman = new Human();
}
}
}
using System.Text;
namespace Practice_2
{
class Teacher : Human
{
public string EducationExperience;
public string SchoolName;
}
}
Details on Abstraction and Encapulations
Details on Abstraction and Encapulations
In C#, abstraction and encapsulation are fundamental object-oriented programming (OOP) principles that help in designing robust, maintainable, and scalable software. Here's a detailed explanation of both concepts:
Abstraction
Definition:
Abstraction is the process of hiding the complex implementation details and showing only the essential features of an object. It allows you to focus on what an object does rather than how it does it.
Purpose:
- To reduce complexity and increase efficiency.
- To manage large and complex systems by breaking them into smaller, manageable parts.
- To hide unnecessary details from the user and expose only what is relevant.
Advantages:
- Improves readability and maintainability: By focusing on the relevant aspects, code becomes easier to read and maintain.
- Promotes reuse: Abstract classes and interfaces can be reused across different parts of the application.
- Enhances flexibility: Changes in implementation do not affect the abstraction, making the system more flexible.
Example in C#:
public abstract class Shape
{
public abstract double GetArea();
}
public class Circle : Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public override double GetArea()
{
return Math.PI * radius * radius;
}
}
public class Square : Shape
{
private double side;
public Square(double side)
{
this.side = side;
}
public override double GetArea()
{
return side * side;
}
}
// Usage
Shape circle = new Circle(5);
Shape square = new Square(4);
Console.WriteLine(circle.GetArea());
Console.WriteLine(square.GetArea());
Encapsulation
Definition:
Encapsulation is the practice of wrapping data (fields) and methods (functions) that operate on the data into a single unit, known as a class. It restricts direct access to some of an object's components and can prevent the accidental modification of data.
Purpose:
- To protect the internal state of an object from unintended or harmful modification.
- To provide a controlled way of accessing and modifying the data.
Advantages:
- Increases security: By hiding the internal state and requiring all interaction to be performed through an object's methods.
- Improves modularity: Each object maintains its own state and behavior, making the system modular.
- Facilitates maintenance: Changes to the internal state or behavior of an object can be made with minimal impact on other parts of the program.
Example in C#:
public class BankAccount
{
private decimal balance;
public decimal Balance
{
get { return balance; }
private set { balance = value; }
}
public void Deposit(decimal amount)
{
if (amount > 0)
{
balance += amount;
}
}
public void Withdraw(decimal amount)
{
if (amount > 0 && amount <= balance)
{
balance -= amount;
}
}
}
// Usage
BankAccount account = new BankAccount();
account.Deposit(1000);
account.Withdraw(500);
Console.WriteLine(account.Balance); // Output: 500
Summary
Abstraction: Focuses on hiding the implementation details and showing only the necessary features. It's used to manage complexity by breaking down large systems into smaller, more manageable parts.
Encapsulation: Focuses on bundling data and methods that operate on the data within a single unit (class) and restricting access to some of the object's components. It's used to protect the internal state of an object and ensure data integrity.
(Practice
Makes A Man Perfect)


No comments:
Post a Comment