Documente Academic
Documente Profesional
Documente Cultură
1.
Class
2.
Object
3.
Variable
4.
Method
5.
Access Modifiers
6.
Encapsulation
7.
Abstraction
8.
Inheritance
9.
Polymorphism
10.
Abstract Class/Method
11.
Virtual Method
12.
Sealed Class/Method
13.
Interface
14.
Static Class/Method
Introduction
There are many explanations that we can find in internet about C# OOP, but here in my article I will give a very
simple example. In this article, I will use a House (like the houses we live in) as a real-time example for easy
understanding of OOP Concept in C#.
1. Class
Class is a like a Blueprint. We can say a House as an example for a Class. In a house, we will have rooms like
living room, bedroom, kitchen and items like TV, fridge etc. House owner can access and use all the rooms and
rooms' items. Same like this in a Class will have a group of Methods and Variables. Rooms and Rooms' Items
are example for Methods and Variables. So now, we have a complete house with all rooms and rooms' items.
House owner can access and use all the rooms and Rooms' Items. To access and use a Class, methods and
variables here we use Objects. Objects are instance of a class. We will see details about objects in the next
section.
What will happen if there are no rooms and items in a House, It will be empty and no one can use the house
until it has all the rooms and Items? See the below image as an example for the empty house.
Now this empty house is a Class .So what is the use of a Class without Methods and variable.
Now lets see an example for a Complete House with Rooms and items.
So here, we have a complete house. Similarly, the Class will be complete with group of Variables, Methods and
Objects. We can see details of all this in next sections of this article.
Class and objects are the base concept of OOP Object Oriented Programming.
Here is an Example of Class -> Class should be started with the Keyword class and next we give the name for
our class we can give any meaning full name as Class Name, next we will have the Open and close brackets.
Collapse | Copy Code
class ShanuHouseClass1
{
}
2. Object
As we have already seen that, House Owner will access and use all the Rooms of the House and its Items.
Similarly, to access all Class Method and Variable we use Objects. We can create one or many object for a same
Class. Example we can say for a house there might be one or many owners.
Here is an example of Object ->Here objHouseOwner is the Object for a class which will be used to access all
variable and Method of a class.
3.Variable
Room's Items like Chair, Bed, Table, etc. are examples of Variable. Variable are used to store our values.
Variables can be local or Global. For Example, we can say if we buy a new TV , TV Service man will come and
setup the TV in our home .He will give his contact number for future contacts .Usually what we do is take a
memo paper and write his contact number and keep it in a common place or in a wallet of ours. If we keep the
memo in a Commonplace everyone who is visiting our house can see that contact number. Global or public
variables are similar to this. If we declared the variable as Global, All the Methods inside the class can access
the variable. If we store the memo Only in our wallet, we can see the contact number. Local or private variables
are similar to this.
Syntax for variable:
Access-Modifiers Data-Type Variable-Name
By default the Access-Modifiers are by private, we can also use public to variable.
Example of Variable:
Collapse | Copy Code
int NoofTV = 0;
public String YOURTVName;
private Boolean DoyouHaveTV = true;
4. Method or Functions:
We have already seen in our article that Rooms are example of Methods.
Note: Most of developers were wondering about what is the difference between the Method and Function, both
Methods and Functions are the same. Here in my article, I will use Method instead of functions. However, there
is one difference in Methods and Functions, In OOP Languages like C#, Java etc. We use the term Method
while the non-OOP programming like C etc. we use the term Function.
What is the use of Methods?
Another real-time example lets take our mobile phone, we can say as we have Mobile phone and store many
Songs in it. However, we always like to listen to the selected songs. It will be boring and hard for us to select
our favorite song every time and play it. Instead of doing the same work repeatedly, we use the playlist. In
playlist, we can add all-favorite songs of ours. Just click on the playlist of our collections and listen to the music.
This will make our work easier and we dont need to do the same thing again and again. Methods are used like
a playlist where we can write all our repeated code in one Method and just call the method wherever we
needed.
Here we can see more details about the Method.
In a house, there might be one big room or multiple rooms but each room will have different facilities, similarly
in a class we can write one or multiple Methods. In a house, there might be two or three Bedrooms. Here the
room name is Bedroom, but each bedroom can be different by size, color etc. This means same Rooms with
different type. Similarly, in a class we can create more than one method with the same name but different
parameter. In OOP its called as Polymorphism we can see details about Polymorphism later on in this article.
Syntax for the Functions
Access-Modifiers Return-Type Method-Name (Parameter-List)
Access-Modifiers: We will see more details about this Topic later on.
Return-Type: If our Method returns any value then we use the return Type with any Data Type as String, int
etc., if our Method does not return any value then we use the type Void.
Method-Name: Here we give our Name for every Method, which we create
Parameter-List: Parameter-List or Arguments, which we pass to the function.
Here is an example of Method ->
Method with Void Type: Void is a keyword which will not return any data from the Method, for example we
can see the below Method with void Type, here in this method we display all our output using the
Console.WriteLine and have used the Console.ReadLine()); to get the Input. This Method has all Input and
Output Operation but this method dont return any value.
Collapse | Copy Code
// Function with void and no parameter -- here void means no return type
public void veranda()
{
Console.WriteLine("Welcome to Veranda");
Console.WriteLine("How Many Chairs Do you have in your Veranda");
NoofChair = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("I have total " + NoofChair + " Chairs in my Veranda");
}
Method with Return Type: Method with return type will return some result, which can be used in our
program, for example, here we have Method TVNAME with return Type as String. We can say in our home we
might have a TV in our LivingROOM and in the parents bedroom and also in kids bedroom .We might have
different TV brand in each room, suppose if we want to know each room TV Brand Name then we need to enter
the same code 3 times. Instead of writing the same code again, we can use a method with Return Type.
Collapse | Copy Code
class ShanuHouseClass1
{
int NoofChair = 0;
public String YOURTVName;
private Boolean DoyouHaveTV = true;
// Function with void and no parameter -- here void means no return type
public void veranda()
{
Console.WriteLine("Welcome to Veranda");
Console.WriteLine("How Many Chairs Do you have in your Veranda");
NoofChair = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("I have total " + NoofChair + " Chairs in my Veranda");
}
// Function with Return type as String
public string TVNAME()
{
Console.WriteLine("Enter Your TV Brand NAME");
YOURTVName = Console.ReadLine();
return YOURTVName;
}
//Function with parameter
public void BedRoom(String nameandColor)
{
Console.WriteLine(nameandColor);
}
// Same Function Name with Different Paramenter
public void BedRoom(String MemberName,String Color)
{
Console.WriteLine(MemberName + " Like " + Color + "Color");
}
static void Main(string[] args)
{
ShanuHouseClass1 objHouseOwner = new ShanuHouseClass1();
objHouseOwner.veranda();
String returnvalue = objHouseOwner.TVNAME();
Console.WriteLine("Your TV BRAND NAME IS: "+returnvalue);
objHouseOwner.BedRoom("My Name is Shanu I like Lavender color");
objHouseOwner.BedRoom("My Name is Afraz I like Light Blue color");
objHouseOwner.BedRoom("SHANU", "Lavender");
Console.ReadLine();
}
}
The Output of above class is here:
5. Access Modifiers:
Access Modifiers are nothing but the Usage and Limitation of our type like variable, Methods and Class. For
Example we can say it as a security limit.
private
public
internal
protected
protected internal
This six are the basic Access modifiers which we used in our C# Class/method and in Variables.
Private:
Lets take our House Example .We will have a Security Guard in House, His duty is to tell the Entrance of the
house. He cannot go inside the house and access all the things. He's private to the House class.
Public:
House Owners are public to the class where they can access all classes related to the House. They have no
restrictions to access their house.
Protected: Servants and Guests are example for the Protected. For Example Servants can go to all room and
do cleaning and other activates. However, they have limitations of access in the house, as they cannot take rest
in a bed of house owner.
Internal: House owners have only access limitation within their house, they cannot enter to neighbor house
and access all the things of neighbor house.
Protected Internal: For example, an owner may have more than one house; in that case, the owner may
access the entire house that belongs to him.
Note: The main and major things we need to know in OOP concept are Encapsulation, Abstraction,
Polymorphism and Inheritance. We will discuss them in detail in this article.
6. Encapsulation:
In our house example, I have already told that House security guard limitation is the entrance of the house. The
security guard doesnt need to know about what is happening inside the house. Therefore, the House Owner will
hide from the Security guard all the happenings for more safety for his safety. The hiding and limitation are
called as Encapsulation.
For example, we have two Classes the first one is Houseclass and the other class as houseSecurityClass
Here we can see all the variables are wrap into a class where houseSecurityClass is set as public, so the
Houseclass can access that, but houseClass has both Public and private variable where the private variable
of a class cannot be accessed outside of the class.
Collapse | Copy Code
7. Abstraction :
Abstraction is to show and share some common information to the user. Lets take our House
example, in our house we will have servant, servants can go to all rooms and do cleaning and other works. The
house owner can give full rights or some partial rights to the servant for accessing his house.
8. Inheritance:
Inheritance is nothing but accessing and using all base class variable and methods in the Derived Class.
Note: Some time users might be not clear of what Base class is and what Derived class is. Base class is the
super class and derived class is the class which inherit the base class.
Here we can see a simple Inheritance where the base class is the GuestVist and derived class is the
HouseOwnerClass. Here HouseOwnerClass class inherits the base class of GuestVist
Collapse | Copy Code
9. Polymorphism :
Ploy means more than one form. In the beginning of the Article at Method Section, we have already seen an
example of Polymorphism. Same method name with different parameter is an example for the polymorphism.
Method Overloading and Method Overriding will be used in polymorphism. Polymorphism have two types
of execution one is Compile Time Polymorphism and the other one is called the Run time Polymorphism.
Method Overloading:
Method overloading are nothing but same Method name will be used for more than one method with different
Argument .
Here is an example program for the Method Overloading .As we can see here Method name BedRoom has
been used for two Method but the parameter for both methods are different.
Collapse | Copy Code
class HouseOwnerClass
{
//Function with parameter
public void BedRoom(String nameandColor)
{
Console.WriteLine(nameandColor);
}
// Same Function Name with Different Paramenter
public void BedRoom(String MemberName, String Color)
{
Console.WriteLine(MemberName + " Like " + Color + "Color");
}
static void Main(string[] args)
{
HouseOwnerClass objHouseOwner = new HouseOwnerClass();
objHouseOwner.BedRoom("My Name is Shanu I like Lavender color");
objHouseOwner.BedRoom("My Name is Afraz I like Light Blue color");
objHouseOwner.BedRoom("SHANU", "Lavender");
Console.ReadLine();
}
}
Method Overriding:
The difference between the Method Overloading and Overriding are.In Method Overloading we will have same
method name with different argument.
In Method Overriding we will have same Method Name same Argument and same type but method overriding
can only be used in the derived class, Method Overriding cannot be done in the same class.
We will see how Method Overriding can be used in Abstract Method, Virtual Method and in Sealed Method
kindly refer to that section in this article.
Abstract class can have both Abstract Method and normal Method. In Abstract Class at least one Abstract
Method should be declared. In addition, derived class should override the abstract method. To access the
abstract method we should use the override keyword in our derived class.
What will happen if we create an abstract method but which is not override in derived class?
Here we can see an abstract class has an abstract method, But the abstract method is not override in the
derived class. See the below image for the warning message displaying as class must implement the abstract
member.
Here we can see an example of Abstract Class and for Abstract Method in detail.
In this example, we can see an abstract class, which has normal Method and Abstract Method. Abstract
Methods; do not have body part in Abstract Class, which means we can only declare an Abstract Method at
Abstract Class, There should be minimum one Abstract Method in an Abstract Class.
Collapse | Copy Code
objHouse.NoofGuestwillvisit();
Console.ReadLine();
}
}
output:
{
OwnerofficialRoom obj = new OwnerofficialRoom();
obj.AllMyPersonalItems();
Console.ReadLine();
}
}
Sealed Method: If we declared a method as sealed that specific method cannot be override in the derived
class.
Lets see our house class here I have base class with Virtual Method and virtual Sealed method.
The Virtual method can be override in the derived class .But the Virtual Sealed Method cannot be override in
sealed class.
Collapse | Copy Code
13. Interface :
Multiple Inheritance:
Will the .Net Support the Multiple Inheritance?
The Answer to this Question is No. In C #, its not possible to write a Multiple Inheritance using Class.
What is Multiple Inheritance? Multiple Inheritance is nothing but we can have more than one class and we can
inherit both Classes in our derived class.
What will happen if I write a Multiple Class Inheritance Using C#?
Lets take our example House .Here we have the derived Class as HouseOwnerClass and have Two More
classes as GuestVist and FriendsandRelationsClass.
Now suppose for our house both Guest and Friend have visited. For this, we write above three classes and
inherit the two classes in our derived class.
When I write the Multiple Inheritance in C #, it will display the warning message during our code and execute
our program. The Warning message will be as Expected and interface
See the below image which shows the Warning error message while I write Multiple Inheritance.
interface GuestInterface
{
void GuestWelcomeMessage();
void NoofGuestes();
}
interface FriendsandRelationsInterface
{
void friendwelcomemessage();
void FriendName();
}
class HouseOwnerClass : GuestInterface, FriendsandRelationsInterface
{
public void GuestWelcomeMessage()
{
Console.WriteLine("All guests are well come to our home");
}
public void NoofGuestes()
{
Console.WriteLine("Total 15 Guestes has visited");
}
public void friendwelcomemessage()
{
Console.WriteLine("Welcome to our Home");
}
public void FriendName()
{
Console.WriteLine("Friend name is: Afraz");
}
static void Main(string[] args)
{
HouseOwnerClass obj = new HouseOwnerClass();
obj.GuestWelcomeMessage();
obj.NoofGuestes();
obj.friendwelcomemessage();
obj.FriendName();
Console.ReadLine();
}
}
The Output will be like this.
In some cases we need to have certain methods which will be used in many derived classes. Each derived can
implement different functionality for those Methods. In These cases, we can use the Interface.
We can say our Guest and house example. For Guest the Welcome Message and No of Guest Function are
common, but it will be different for different owners in the same house, Guest might a fathers guest, Mothers
Guest, Childrens Guest or Family Guest. Each guest can have different welcome message subject, but the
functions are same as Message .lets consider now Father is a Class, Mother is a class and Children are one
Class. Both guestWelcome Message and Noofguest method are same for all. In this case, we can create an
Interface and declare both methods in the Interface. All father, mother and Children Classes can inherit the
interface and write their own method details.
Interface is similar to Abstract class but the major difference between the Abstract Class and the Interface are
.In Abstract Class there can be both Abstract Method and Non Abstract methods .But in Interface all methods
are abstract by default which means there is no non Abstract type method in the Interface. All the Methods
declared in Interface should be override in the derived class.
What will happen when non-abstract methods with body part are declared in an Interface?
It will display the warning message as unexpected modifier in Access modifier part and Unexpected Method
body error warning at message Body. See the below image for the details.
interface GuestInterface
{
void GuestWelcomeMessage();
void NoofGuestes();
}
class HouseOwnerClass: GuestInterface
{
public void GuestWelcomeMessage()
{
Console.WriteLine("All guests are well come to our home");
}
public void NoofGuestes()
{
Console.WriteLine("Total 15 Guestes has visited");
}
static void Main(string[] args)
{
HouseOwnerClass obj = new HouseOwnerClass();
obj.GuestWelcomeMessage();
obj.NoofGuestes();
Console.ReadLine();
}
}
We have already learned about what is Sealed Class in this Article; now lets see what are Static Class and
Static Method.
Both Static and Sealed Class cannot be inherited.
What is the Difference between Static Class and Sealed Class?
We can create an Object (instance) for the Sealed Class, we can see in my sealed class section I have created a
sample Sealed class and in Main Method I have created an object to access the sealed Class. And in a Sealed
Class both Static and non-Static methods can be written.
But for a Static Class its not possible to create an Object. In Static Class only Static members are allowed which
means in a static Class its not possible to write non-static method.
We can say our main method as an example for the Static method. When we create a console application in c#
we can see each class will have a default main class. In my article I have explained that when an Console or
Windows application start execute first the main method will be executed first .There is no need to create an
object for the main method since it was been declared as a static method.
What will happen when we create an object for the Static class?
Lets see an example when I try to create an object for my Static Class.
When we run the program we get the error message as Can not create an instance of a static
class .Sorry Im using the Korean Version of Visual Studio so the error message in Korean language.
How to call the Static Class the Method and variable without creating the Object?
Its simple just we can use the ClassName.Variable or Method Name for example
OwnerofficialRoom.AllMyPersonalItems();
See the below example with Static class