Class definition
A class is a group of related methods and variables.
A class is
a construct that enables you to create your own custom types by grouping
together variables of other types, methods and events. A class is like a
blueprint. It defines the data and behavior of a type. If the class is not
declared as static, client code can use it by creating objects or instances which
are assigned to a variable. The variable remains in memory until all references
to it go out of scope. At that time, the CLR marks it as eligible for garbage
collection. If the class is declared as static, then only one copy exists in memory and client code can only
access it through the class itself, not an instance variable. For more information. classes support inheritance,
a fundamental characteristic of object-oriented programming. Classes are declared by using the class keyword.
public class
Customer
{
//Fields, properties, methods and events go here...
}
/***********************************************/
namespace ConsoleApplication1
{
class Program
{
static
void
Main(string[] args)
{
Car objCar = new Car();
objCar.NonStaticMethod();
Bus.StaticMethod();
}
}
class Car
{
public
string
NonStaticMethod()
{
return
"NonStatic";
}
}
class Bus
{
public
static
string
StaticMethod()
{
return
"Static Mathod";
}
}
}
It is a real time entity.
An object can be considered
a "thing" that can perform a set of related activities. The set of
activities that the object performs defines the object's behavior. For
example, the hand can grip something or a Student (object) can give the
name or address. In pure OOP terms an object is an instance of a class
Encapsulation
Encapsulation is way to
hide data, properties and methods from outside the world or
outside of the class scope and exposing only necessary thing.Encapsulation complements Abstraction. Abstraction display only important features of a class and Encapsulation hides unwanted data or private data from outside of a class.It hides the information within the object and prevents from accidental corruption.
outside of the class scope and exposing only necessary thing.Encapsulation complements Abstraction. Abstraction display only important features of a class and Encapsulation hides unwanted data or private data from outside of a class.It hides the information within the object and prevents from accidental corruption.
How We Can Achieve Encapsulation
We can achieve Encapsulation by using "private","Public","Protected","Internal",Protected Internal" access modifier as shown in below snippet of code
Why to use Encapsulation
Encapsulation means
protecting important data inside the class which we do not
want to be exposed outside of the class.
want to be exposed outside of the class.
If you have seen
important TV machine, TV connections and TV color tube is hidden inside
the TV case which is not been exposed for viewers like us and exposed
only neccessary things of a TV like TV Channel keys, TV volume keys,
ON/OFF switch, Cable Switch and TV remote control for viewers to use
it.This means TV machine, TV connections and TV color tube is an unwanted data
and not needed for viewers to see is been hidden from outside the world.
So encapsulation
means hiding the important features of a class which is not been needed to
be exposed outside of a class and exposing only necessary things of a class.
Here hidden part of
a class acts like Encapsulation and exposed part of a class acts like
Abstraction.
class clsTelevision
{
private void TVmachine()
{
Console.WriteLine("Machine of a Television");
}
private void TVcolortube()
{
Console.WriteLine("Color Tube of a Television");
}
public void TVKeys()
{
Console.WriteLine("Keys of a Television");
}
public void TVRemote()
{
Console.WriteLine("Remote of a Television");
}
public void TVScreen()
{
Console.WriteLine("Wide Screen of a Television");
}
}
So as you can see from
our above code that we have hidden core part of a television methods by
using "private" access modifier and exposed only
necessary methods for a viewers to use it using "public" access modifier.
Access Specifiers in C#
Access Specifiers in C#
Access
Specifiers defines the scope of a class member. A class member can be variable
or function
Public
The
class member, that is defined as public can be accessed by other class member that is
initialized outside the class. A public member can be accessed from anywhere even
outside the namespace
Private
The private access specifiers restrict the member variable or function to be called outside from the parent class. A private function or variable cannot be called outside from the same class. It
hides its member variable and method from other class and methods.
However, you can store or retrieve value from private access modifiers using get set property.
Protected
The protected access specifier hides its member variables and functions from other classes and objects. This type of variable or function can only be accessed in child class. It becomes very
important while implementing inheritance.
Internal
The internal access specifier hides its member variables and methods from other classes and objects, that is resides in other namespace. The variable orclasses that are declared with internal can
be access by any member within application. It is the default access specifiers
for a class in C# programming.
Protected Internal
The protected internal access specifier allows its members to be accessed in
derived class, containing class or classes within same application.
However, this access specifier rarely used in C# programming but it becomes
important while implementing inheritance
namespace
AccessModifiers
{
//public
class access
{
public string name;
public void print()
{
Console.WriteLine("Hello:" + name);
}
}
//private
class privateaccess
{
private string name;
public void print()
{
Console.WriteLine("Hello:" + name);
}
}
//protected
class protectedaccess
{
protected string name;
public void print()
{
Console.WriteLine("Hello:" + name);
}
}
//internal
class Internalaccess
{
internal string name1;
public void print1()
{
Console.WriteLine("Hello:" + name1);
}
}
class Program
{
static void Main(string[] args)
{
access obj = new access();
obj.name="SHANKAR";
obj.print();
privateaccess obj1 = new privateaccess();
onj.name //you cannot call name variable outside
the class
obj.print();
protectedaccess obj2 = new protectedaccess();
obj2.name //the protected member can only be
accessed within its child class. in inheritance it will applicable
Internalaccess obj3 = new Internalaccess();
obj3.name1 = "SHANKAR";
obj3.print1();
Console.Read();
}
}
}
GET and SET methods
GET and SET methods
The
get set accessor or modifier mostly used for storing and retrieving value from the private field. The get accessor must return a value of property type where set accessor returns void. The set accessor
uses an implicit parameter called value. In simple word, the get method used
for retrieving
value from private field whereas set method used
for storing
value in private variables.
class getset
{
// String Variable declared as private
private
static
string
name;
public
void
print()
{
Console.WriteLine("\nMy name is " + name);
}
public
string
Name //Creating Name property
{
get //get method for returning value
{
return name;
}
set // set method for storing value in name field.
{
name = value;
}
}
}
class
Program
{
static
void
Main(string[] args)
{
getset
obj4 = new getset();
Console.Write("Enter your name:\t");
obj4.Name = Console.ReadLine();
obj4.print();
Console.Read();
}
}
Data Abstraction
Abstraction
is just opposite of Encapsulation. Abstraction is mechanism to show only
relevant data to the user. Consider the mobile example. Whenever you buy a mobile phone, you see
their different types of functionalities as camera, mp3 player,
calling function, recording function, multimedia etc. It is abstraction,
because you are seeing only relevant information instead of their internal engineering.
The word abstract means a concept or an idea not
associated with any specific instance.
In programming we apply the same meaning of abstraction by making classes not associated with any specific instance.
The abstraction is done when we need to only inherit from a certain class, but not need to instantiate objects of that class. In such case the base
class can be regarded as "Incomplete". Such classes are known as an "Abstract Base Class".
In programming we apply the same meaning of abstraction by making classes not associated with any specific instance.
The abstraction is done when we need to only inherit from a certain class, but not need to instantiate objects of that class. In such case the base
class can be regarded as "Incomplete". Such classes are known as an "Abstract Base Class".
Abstract Base Class
There are some important points about Abstract Base Class :
- An
Abstract Base class can not be instantiated; it means the object of that
class can not be created.
- Class
having abstract keyword and having, abstract keyword with some of its
methods (not all) is known as an Abstract Base Class.
- Class
having Abstract keyword and having abstract keyword with all of its
methods is known as pure Abstract Base Class.
- The
method of abstract class that has no implementation is known as
"operation". It can be defined as abstract void method ();
- An
abstract class holds the methods but the actual implementation of those
methods is made in derived class.
- Lets
have a look of this code!
abstract class animal{public abstract void eat();public void sound(){Console.WriteLine("dog can sound");}}This is the Abstract Base Class, if I make both of its methods abstract then this class would become a pure Abstract Base Class.
Now we derive a class of 'dog' from the class animal.
abstract class animal{public abstract void eat();public void sound(){Console.WriteLine("dog can sound");}}class dog : animal{public override void eat(){Console.WriteLine("dog can eat");}} - Here
you can see we have 2 methods in the Abstract Base Class, the method eat()
has no implementation; that is why it is being declared as 'abstract'
while the method sound() has its own body so it is not declared as
'abstract'.
- In
the derived class we have the same name method but this method has it's
body.
We are doing abstraction here so that we can access the method of derived class without any trouble.
Let's have a look!
class program
class program
{
abstract
class
animal
{
public
abstract void eat();
public
void
sound()
{
Console.WriteLine("dog can sound");
}
}
class
dog
: animal
{
public
override void eat()
{
Console.WriteLine("dog can eat");
}
}
static
void
Main(string[] args)
{
dog mydog = new dog();
animal
thePet = mydog;
thePet.eat();
mydog.sound();
}
}
Finally we created an Object 'mydog' of class dog,
but we didn't instantiate any object of Abstract Base Class 'animal'.
Inheritance
Inheritance is one of the primary
concepts of object-oriented programming. Inheritance describes the ability
to create new classes based on an existing class.
you can save lot of time in your programming and also
reduce errors, which in turn will increase the quality of work and
productivity.
Using System;
Public class BaseClass
{
Public BaseClass ()
{
Console.WriteLine ("Base Class Constructor executed");
}
Public void Write ()
{
Console.WriteLine ("Write method in Base Class executed");
}
}
Public class ChildClass: BaseClass
{
Public ChildClass ()
{
Console.WriteLine("Child Class Constructor executed");
}
Public static void Main ()
{
ChildClass CC = new ChildClass ();
CC.Write ();
}
}
In the Main () method
in ChildClass we create an instance of childclass. Then we call the write ()
method. If you observe the ChildClass does not have a write() method in it.
This write () method has been inherited from the parent BaseClass.
In C# Multi-Level inheritance is possible. Code
snippet below demonstrates mlti-level inheritance. Class B is derived from
Class A. Class C is derived from Class B. So class C, will have access to all
members present in both Class A and Class B. As a result of multi-level
inheritance Class has access to A_Method(),B_Method() and C_Method().
Using System;
Public class A
{
Public void A_Method ()
{
Console.WriteLine ("Class A Method Called");
}
}
Public class B: A
{
Public void B_Method ()
{
Console.WriteLine ("Class A Method Called");
}
}
Public class C: B
{
Public void C_Method ()
{
Console.WriteLine ("Class A Method Called");
}
Public static void Main ()
{
C C1 = new C ();
C1.A_Method ();
C1.B_Method ();
C1.C_Method ();
}
}
Interfaces
- An interface looks like a class, but has no implementation. The only thing it contains are declarations of events, methods.
- The reason interfaces only provide declarations is because they are inherited by structs and classes, that must provide an implementation for each interface member declared.
- by using interface concept we can achieve multiple inheritance, means one class can implement more than one interfaces.
- the most important use for interfaces is to reduce coupling between components in your software.
- An interface allows to represent an agreement between classes on how they will talk to each other without being tied to the actual implementations.
interface IOne
{
void ONE();//Pure Abstract Method Signature
}
interface ITwo
{
void TWO();
}
class Number
: IOne, ITwo//Must Implement all the abstract method, in Derived
class.
{
public
void
ONE()//Implementation of Abstract
Method.
{
Console.WriteLine("This is one");
}
public
void
TWO()//Implementation of Abstract
Method.
{
Console.WriteLine("This is two");
}
}
namespace InterfacesApp
{
class
Program
{
static
void
Main(string[] args)
{
IOne obj = new Number();
{
obj.ONE();
}
ITwo obj1 = new Number();
{
obj1.TWO();
}
Console.Read();
}
}
}
-----------------------------------------------------------------------------------------------------------
interface abc
{
int x;
}
Interfaces in C# cannot
contain fields i.e variables
interface abc
{
void xyz()
{
System.Console.WriteLine("In xyz");
}
}
It
told us loudly that interface members cannot have a defination.
class Demo
{
public
static
void
Main()
{
System.Console.WriteLine("Hello Interfaces");
}
}
interface abc
{
void xyz();
}
The above program
compiles and runs successfully to produce the desired output. Finally we made
the compiler happy. Interfaces in C# can only contain function declarations.
Now let us see interfaces in action.
So its time to perform
the marriage between our groom class
Demo
and the bride interface abc
.
class Demo : abc
{
public
static
void
Main()
{
System.Console.WriteLine("Hello Interfaces");
xyz();
}
public
void
xyz()
{
System.Console.WriteLine("In xyz");
}
}
interface abc
{
void xyz();
}
The above program compiles and runs successfully
to produce the desired output
Polymorphism
Polymorphism means many forms (ability to take more
than one form). In Polymorphism poly means “multiple” and morph means “forms”
so polymorphism means many forms.
In polymorphism we will declare methods with same name
and different parameters in same class or methods with same name and same
parameters in different classes. Polymorphism has ability to provide different
implementation of methods that are implemented with same name.
In Polymorphism we have 2 different types those are
- Compile Time Polymorphism (Called as Early
Binding or Overloading or static binding)
- Run Time Polymorphism (Called as Late
Binding or Overriding or dynamic binding)
Compiletime Polymorphism
Compile time polymorphism means we will declare
methods with same name but different signatures because of this we will perform
different tasks with same method name. This compile time polymorphism also
called as early binding or method overloading.
Method Overloading or compile time polymorphism means
same method names with different signatures (different parameters)
public class Class1
{
public void NumbersAdd(int a, int b)
{
Console.WriteLine(a + b);
}
public void NumbersAdd(int a, int b, int c)
{
Console.WriteLine(a + b + c);
}
}
In above class we have two methods with same name but
having different input parameters this is called method overloading or compile
time polymorphism or early binding.
RunTime Polymorphism
Run time polymorphism also called as late binding or
method overriding or dynamic polymorphism. Run time polymorphism or method
overriding means same method names with same signatures.
In this run time polymorphism or method overriding we
can override a method in base class by creating similar function in derived
class this can be achieved by using inheritance principle and using “virtual
& override” keywords.
In base class if we declare methods with virtual
keyword then only we can override those methods in derived class using override
keyword
//Base Class
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base Class");
}
}
// Derived Class
public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using base and derived class
class Program
{
static void Main(string[] args)
{
// calling the overriden method
DClass objDc = new DClass();
objDc.Sample1();
// calling the base class method
Bclass objBc = new DClass();
objBc.Sample1();
}
}
If we run above code we will get output like as shown below
Derived Class
Derived Class
Partial Class
Partial class is a new feature added to C# 2.0 and Visual Studio 2005.It is possible to split the definition of a class.Each source file contains a section of the class definition, and all parts are combined when the application is compiled.When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
Partial Class
Partial class is a new feature added to C# 2.0 and Visual Studio 2005.It is possible to split the definition of a class.Each source file contains a section of the class definition, and all parts are combined when the application is compiled.When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
partial class MyClass : IF1, IF2, IF3
{
// main
implementation of MyClass
}
partial class MyClass
{
//
implementation of IF1
}
partial class MyClass
{
//
implementation of IF2
}
No comments:
Post a Comment