Object-Oriented Programming Concepts in C#
Oops
known as object-oriented programming language system
·
Abstraction
·
Encapsulation
·
Inheritance
and
·
Polymorphism
Object-Oriented
Programming (OOP) is a programming structure where programs are organized
around objects as opposed to action and logic. Everything in oops placed
together works as a self-contained object. An object is a combination of
variable and function and data can perform a set of relevant activity.
Important Features of OOP
Class
A class is a collection of method and variables. It is a blueprint that
defines the data and behavior of a type. You are required to create an
instance/object of a class stating what operation can be performed on that
object. Objects are instances of a class. The methods and variables that
constitute a class are called members of the class.
Object
An object is a runtime entity of an object-oriented programming
system. An object can be created by using the new keyword to allocate memory
for the class in heap, the object is called an instance and its starting
address will be stored in the object in stack memory
Abstraction
Abstraction is a principle of
object oriented programming language (OOP) and it is used to hide the
implementation details and display only essential features of the object.
Abstraction
is one of the principles of object oriented programming. It is used to display
only necessary and essential features of an object to outside the world. Means
displaying what is necessary and encapsulate the unnecessary things to outside
the world. Hiding can be achieved by
using "private" access modifiers.
Abstraction can be achieved using abstract classes in C#.
Abstraction and encapsulation are
related features in object-oriented programming. Abstraction allows making relevant
information visible and encapsulation enables a programmer to implement the
desired level of abstraction.
Note - Outside the world means when we use reference of object then it will show only necessary methods and properties and hide methods which are not necessary.
Note - Outside the world means when we use reference of object then it will show only necessary methods and properties and hide methods which are not necessary.
In
object oriented programming, class is the perfect example
for abstraction. In c#, we can create a class with required methods, properties and we can expose only
necessary methods and properties using access modifiers based on our
requirements.
Here,
the public modifier is used to allow a defined fields, properties and methods to access outside of
the class and the private modifier is used to hide or restrict an access of
required fields, properties and methods from the outside
of class.
using System;
using System.Text;
namespace Tutlane
{
public class Laptop
{
private string brand;
private string model;
public string Brand
{
get { return brand; }
set { brand
= value; }
}
public string Model
{
get { return model; }
set { model
= value; }
}
public void LaptopDetails()
{
Console.WriteLine("Brand: " + Brand);
Console.WriteLine("Model: " + Model);
}
public void LaptopKeyboard()
{
Console.WriteLine("Type using
Keyword");
}
private void MotherBoardInfo()
{
Console.WriteLine("MotheBoard
Information");
}
private void InternalProcessor()
{
Console.WriteLine("Processor
Information");
}
}
class Program
{
static void Main(string[] args)
{
Laptop l = new Laptop();
l.Brand = "Dell";
l.Model = "Inspiron 14R";
l.LaptopDetails();
Console.WriteLine("\nPress Enter
Key to Exit..");
Console.ReadLine();
}
}
}
C#
Encapsulation
In c#, Encapsulation is
a process of binding the data members and member functions into a
single unit.
In c#, class is the real time example for
encapsulation because it will combine a various type of data members and member functions into a single unit.
Generally, in c# the encapsulation is
used to prevent an alteration of code (data)
accidently from the outside of functions.
In c#, by defining the class fields
with properties we
can protect the data from accidental corruption.
If we define a class fields with properties,
then the encapsulated class won’t allow us to access the fields directly,
instead we need to use getter and setter functions to read or write a data based on our requirements.
C# allows encapsulation of data through the use of
accessors (to get data) and mutators (to modify data), which help in
manipulating private data indirectly without making it public.
The following are the benefits of
encapsulation:
- Protection of data from
accidental corruption
- Specification of the
accessibility of each of the members of a class to the code outside the
class
- Flexibility and extensibility
of the code and reduction in complexity
- Lower coupling between objects
and hence improvement in code maintainability
- As in encapsulation, the data
in a class is hidden from other classes, so it is also known as data-hiding.
Encapsulation is used to restrict access to
the members of a class so as to prevent the user of a given class from
manipulating objects in ways that are not intended by the designer
Following access modifiers:
- Public: Access to all code in
the program
- Private: Access to only members
of the same class
- Protected: Access to members of
same class and its derived classes
- Internal: Access to current
assembly
- Protected Internal: Access to
current assembly and types derived from containing class
Abstract classes are the way to achieve
abstraction in C#. Abstraction in C# is the process to hide the internal
details and showing functionality only. Abstraction can be achieved by two
ways:
1. Abstract
class
2. Interface
Abstract class and interface both can have
abstract methods which are necessary for abstraction.
using System;
public class
DemoEncap {
// private variables declared
//
these can only be accessed by
//
public methods of class
private String studentName;
private int
studentAge;
//
using accessors to get and
//
set the value of studentName
public String Name
{
get
{
return studentName;
}
set
{
studentName
= value;
}
}
//
using accessors to get and
//
set the value of studentAge
public int
Age
{
get
{
return studentAge;
}
set
{
studentAge
= value;
}
}
}
//
Driver Class
class GFG {
// Main Method
static public
void Main()
{
// creating object
DemoEncap
obj = new DemoEncap();
// calls set accessor of the property Name,
//
and pass "Ankita" as value of the
//
standard field 'value'
obj.Name
= "Ankita";
//
calls set accessor of the property Age,
//
and pass "21" as value of the
//
standard field 'value'
obj.Age
= 21;
// Displaying values of the variables
Console.WriteLine("Name:
" + obj.Name);
Console.WriteLine("Age:
" + obj.Age);
}
}
Advantages of
Encapsulation:
·
Data Hiding: The
user will have no idea about the inner implementation of the class. It will not
be visible to the user that how the class is stored values in the variables. He
only knows that we are passing the values to accessors and variables are
getting initialized to that value.
·
Increased Flexibility: We
can make the variables of the class as read-only or write-only depending on our
requirement. If we wish to make the variables as read-only then we have to only
use Get Accessor in the code. If we wish to make the variables as write-only
then we have to only use Set Accessor.
·
Reusability: Encapsulation
also improves the re-usability and easy to change with new requirements.
·
Testing code is easy: Encapsulated
code is easy to test for unit testing.
Why do we need encapsulation
The need of encapsulation is to protect or prevent the code
(data) from accidental corruption due to the silly little errors that we are
all prone to make
C# Inheritance
In C#, inheritance is a process in which one object acquires all
the properties and behaviors of its parent object automatically. In such way,
you can reuse, extend or modify the attributes and behaviors which is defined
in other class.
In C#, the class which inherits the members of another class is
called derived class and the class whose
members are inherited is called base class.
The derived class is the specialized class for the base class.
Derived classes can also override inherited
members by providing an alternate implementation. Define derived classes that
either inherit or override that functionality.
C# does not support multiple inheritance, which
means a class can derive from one base class only, although a class can be
derived from one or more interfaces.
Advantage of
C# Inheritance
The main features of
inheritance include:
- All the members of the base
class except those with private accessibility can be accessed in the
derived class.
- All the members of the base
class are inherited from the base class except constructors and
destructors.
- Unlike in C++, the virtual
methods in a derived class need to use the modifier "override"
to override an inherited member.
- To hide an inherited member
with the same name and signature in the derived class, the "new"
modifier can be used.
- To prevent direct instantiation
of a class, the "abstract" modifier can be used.
- To prevent further derivation
of a base class, it can be declared using "sealed" modifier.
Inheritance provides the
following benefits:
- It enables the construction of
a hierarchy of related classes that can reuse, extend and alter the
behaviors defined in the existing classes.
- It allows code reuse, reducing
time and effort in coding and testing.
- It helps improve modularity and
performance by dividing large pieces of code into smaller, more
manageable, pieces.
- It forms the means to achieve
polymorphism, which allows an object to represent more than one type.
C#
Polymorphism
Polymorphism means
providing an ability to take more than one form.
The polymorphism is a combination of two words, one is poly and another one is
morphs. Here poly means “multiple” and morphs means “forms” so polymorphism
means many forms.
In c#, polymorphism provides an ability for the classes to
implement a different methods that are called through the same name and it also
provides an ability to invoke the methods of derived class through base class
reference during runtime based on our requirements.
Polymorphism :-
Static or Compile Time Polymorphism
Method overloading is an example of Static Polymorphism. In
overloading, the method / function has a same name but different
signatures.
Dynamic / runtime polymorphism is also known as late binding.
(Method overriding)
Dynamic / runtime polymorphism is also known as late binding.
Here, the method name and the method signature (number of parameters and
parameter type must be the same and may have a different implementation).
---------------------------------------------------------------------
In c#, we have a two different kind of polymorphisms available,
those are
1) Compile Time /Static /Early binding /Method overloading
Polymorphism
2) Run Time /Dynamic /late binding. (Method overriding)
Polymorphism
1) Method overloading :- A multiple methods with same name but
with different parameters. By using compile time polymorphism, we can perform a
different tasks with same method name by passing different parameters. the
compile time polymorphism can be achieved by using method overloading and it is
also called as early binding or static binding.
using System;
namespace Tutlane
{
public class Calculate
{
public void AddNumbers(int a, int b)
{
Console.WriteLine("a + b = {0}", a + b);
}
public void AddNumbers(int a, int b,
int c)
{
Console.WriteLine("a + b + c = {0}", a + b + c);
}
}
class Program
{
static void Main(string[] args)
{
Calculate c = new
Calculate();
c.AddNumbers(1, 2);
c.AddNumbers(1, 2, 3);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
2) Method overriding :- Run Time Polymorphism means overriding a
base class method in derived class by creating a similar function and this can
be achieved by using override & virtual keywords along with inheritance
principle.
a method with same name and parameters to perform a different
task.
Example :-
1) Create a class hierarchy in which each specific shape class
derives from a common base class.
2) Use a virtual method to invoke the appropriate method on any
derived class through a single call to the base class method.
First, create a base class called Shape, and derived classes such
as Rectangle, Circle, and Triangle. Give the Shape class a virtual method
called Draw, and override it in each derived class to draw the particular shape
that the class represents. Create a List<Shape> object and add a Circle,
Triangle and Rectangle to it. To update the drawing surface, use a foreach loop
to iterate through the list and call the Draw method on each Shape object in
the list. Even though each object in the list has a declared type of Shape, it
is the run-time type (the overridden version of the method in each derived
class) that will be invoked.
using System;
using System.Collections.Generic;
public class Shape
{
// A few example members
public int X { get; private set; }
public int Y { get; private set; }
public int Height { get; set; }
public int Width { get; set; }
// Virtual method
public virtual void Draw()
{
Console.WriteLine("Performing
base class drawing tasks");
}
}
class Circle : Shape
{
public override void Draw()
{
// Code to draw a circle...
Console.WriteLine("Drawing a
circle");
base.Draw();
}
}
class Rectangle : Shape
{
public override void Draw()
{
// Code to draw a rectangle...
Console.WriteLine("Drawing a rectangle");
base.Draw();
}
}
class Triangle : Shape
{
public override void Draw()
{
// Code to draw a triangle...
Console.WriteLine("Drawing a
triangle");
base.Draw();
}
}
class Program
{
static void Main(string[] args)
{
// Polymorphism at work #1: a
Rectangle, Triangle and Circle
// can all be used whereever a Shape
is expected. No cast is
// required because an implicit
conversion exists from a derived
// class to its base class.
var shapes = new List<Shape>
{
new Rectangle(),
new Triangle(),
new Circle()
};
// Polymorphism at work #2: the
virtual method Draw is
// invoked on each of the derived
classes, not the base class.
foreach (var shape in shapes)
{
shape.Draw();
}
// Keep the console open in debug
mode.
Console.WriteLine("Press any key
to exit.");
Console.ReadKey();
}
}
/* Output:
Drawing a rectangle
Performing base class drawing tasks
Drawing a triangle
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks
*/
It has two distinct aspects:
1) At run time, objects of a derived class may be treated as
objects of a base class in places such as method parameters and collections or
arrays. When this occurs, the object's declared type is no longer identical to
its run-time type.
2) Base classes may define and implement virtual methods, and
derived classes can override them, which means they provide their own
definition and implementation. At run-time, when client code calls the method,
the CLR looks up the run-time type of the object, and invokes that override of
the virtual method.
Virtual methods enable you to work with groups of related objects
in a uniform way.
Note :- In C#, every type is polymorphic because all types,
including user-defined types, inherit from Object.
Polymorphism Overview
Virtual Members
Abstract Class
An abstract class is an incomplete class or special class we
can't be instantiated. The purpose of an abstract class is to provide a
blueprint for derived classes.
An abstract class can
contain either abstract methods or non abstract methods. Abstract members do
not have any implementation in the abstract class, but the same has to be
provided in its derived class.
The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in
a derived class. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common
definition of a base class that multiple derived classes can share.
Abstract classes may also
define abstract methods.
public abstract class A
{
public abstract void DoWork(int i);
}
Abstract methods have no
implementation, so the method definition is followed by a semicolon instead of
a normal method block. Derived classes of the abstract class must implement all
abstract methods. When an abstract class inherits a virtual method from a base
class, the abstract class can override the virtual method with an abstract
method
An abstract class is a special type of class that
cannot be instantiated. An abstract class is designed to be inherited by
subclasses that either implement or override its methods. In other words,
abstract classes are either partially implemented or not implemented at all.
You can have functionality in your abstract class—the methods in an abstract
class can be both abstract and concrete. An abstract class can have
constructors—this is one major difference between an abstract class and an
interface. You can take advantage of abstract classes to design components and
specify some level of common functionality that must be implemented by derived
classes.
Implementation is completed when a
derived class inherits from it. Abstract classes contain abstract methods,
which are implemented by the derived class. The derived classes have more
specialized functionality.
The following are some of the key points −
·
You cannot create an instance of an abstract class
·
You cannot declare an abstract method outside an abstract class
·
When a class is declared sealed, it cannot be inherited, abstract
classes cannot be declared sealed.
Abstract Base Class
There are some important points about Abstract Base Class :
- An
Abstract Base class cannot be instantiated; it means the object of that
class cannot be created.
- Class
having the abstract keyword with some of its methods (not all) is known as
an Abstract Base Class.
- Class
having the Abstract keyword with all of its methods is known as pure
Abstract Base Class.
- The
method of the abstract class that has no implementation is known as
"operation". It can be defined as an abstract void method ();
- An
abstract class holds the methods but the actual implementation of those
methods is made in derived class.
Abstract
Classes
·
An abstract class is declared with
the help of abstract keyword.
·
In C#, you are not allowed
to create objects of the abstract class. Or in other words, you cannot use the
abstract class directly with the new operator.
·
Class that contains the abstract
keyword with some of its methods(not all abstract method) is known as an Abstract
Base Class.
·
Class that contains the abstract
keyword with all of its methods is known as pure Abstract Base Class.
·
You are not allowed to declare the
abstract methods outside the abstract class.
Important
Points:
·
Generally, we use abstract class at
the time of inheritance.
·
A user must use the override keyword before the method which is
declared as abstract in child class, the abstract class is used to inherit in
the child class.
·
An abstract class cannot be
inherited by structures.
·
It can contains constructors or
destructors.
·
It can implement functions with
non-Abstract methods.
·
It cannot support multiple
inheritance.
·
It can’t be static.
C# Abstract Class Features
- An
abstract class can inherit from a class and one or more interfaces.
- An
abstract class can implement code with non-Abstract methods.
- An
Abstract class can have modifiers for methods, properties etc.
- An
Abstract class can have constants and fields.
- An
abstract class can implement a property.
- An
abstract class can have constructors or destructors.
- An
abstract class cannot be inherited from by structures.
- An
abstract class cannot support multiple inheritance.
C#
Abstract class
In C#, abstract class is a class which is declared abstract. It
can have abstract and non-abstract methods. It cannot be instantiated. Its implementation
must be provided by derived classes. Here, derived class is forced to provide
the implementation of all the abstract methods.
Abstract
Method
A method which is declared abstract and has no body is called
abstract method. It can be declared inside the abstract class only. Its
implementation must be provided by derived classes.
C# Interface
Interface in C# is a blueprint of a class. It is
like abstract class because all the methods which are declared inside the
interface are abstract methods. It cannot have method body and cannot be
instantiated.
It is used to achieve multiple inheritance which can't be
achieved by class. It is used to
achieve fully abstraction because it cannot have method body.
Its implementation must be provided by class or struct.
The class or struct which implements the interface must provide the
implementation of all the methods declared inside the interface.
Note: Interface methods are public and abstract
by default. You cannot explicitly use public and abstract keywords for an
interface method.
Difference between
Abstract Class and Interface
ABSTRACT CLASS
|
INTERFACE
|
It contains both
declaration and definition part.
|
It contains only a
declaration part.
|
Multiple inheritance is
not achieved by abstract class.
|
Multiple inheritance is
achieved by interface.
|
It can contain static
members.
|
It does not contain
static members.
|
It can contain different
types of access modifiers like public, private, protected etc.
|
It only contains public
access modifier because everything in the interface is public.
|
The performance of an
abstract class is fast.
|
The performance of
interface is slow because it requires time to search actual method in the
corresponding class.
|
It is used to implement
the core identity of class.
|
It is used to implement
peripheral abilities of class.
|
A class can only use one
abstract class.
|
A class can use multiple
interface.
|
If many implementations
are of the same kind and use common behavior, then it is superior to use
abstract class.
|
If many implementations
only share methods, then it is superior to use Interface.
|
Abstract class can
contain methods, fields, constants, etc.
|
Interface can only
contain methods.
|
It can be fully,
partially or not implemented.
|
It should be fully
implemented.
|
Feature
|
Interface
|
Abstract
class
|
Multiple
inheritance
|
A
class may inherit several interfaces.
|
A
class may inherit only one abstract class.
|
Default
implementation
|
An
interface cannot provide any code, just the signature.
|
An
abstract class can provide complete, default code and/or just the details
that have to be overridden.
|
Access
Modfiers
|
An
interface cannot have access modifiers for the subs, functions, properties
etc everything is assumed as public
|
An
abstract class can contain access modifiers for the subs, functions,
properties
|
Core
VS Peripheral
|
Interfaces
are used to define the peripheral abilities of a class. In other words both
Human and Vehicle can inherit from a IMovable interface.
|
An
abstract class defines the core identity of a class and there it is used for
objects of the same type.
|
Homogeneity
|
If
various implementations only share method signatures then it is better to use
Interfaces.
|
If
various implementations are of the same kind and use common behaviour or
status then abstract class is better to use.
|
Speed
|
Requires
more time to find the actual method in the corresponding classes.
|
Fast
|
Adding
functionality (Versioning)
|
If
we add a new method to an Interface then we have to track down all the
implementations of the interface and define implementation for the new
method.
|
If
we add a new method to an abstract class then we have the option of providing
default implementation and therefore all the existing code might work
properly.
|
Fields
and Constants
|
No
fields can be defined in interfaces
|
An
abstract class can have fields and constrants defined
|
No comments:
Post a Comment