oops csharp

Upload: ksurimca

Post on 30-May-2018

338 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 OOPs CSharp

    1/43

    OOPs

    Object Oriented ProgrammingSynopsis

  • 8/9/2019 OOPs CSharp

    2/43

  • 8/9/2019 OOPs CSharp

    3/43

    Features of OOPs language

    1. Emphasis on data rather than

    procedure.2. Program divided into objects (class).

    3. Data is hidden and can not beaccessed by external functions.

    4. Follows bottom-Up approach.

  • 8/9/2019 OOPs CSharp

    4/43

    An object oriented programmingmethod has many advantages,

    some of them are flexibility andcode reusability.

    All the programming languagessupporting Object oriented

    Programming will be supportingthese three main concepts:

  • 8/9/2019 OOPs CSharp

    5/43

    About Object Oriented LanguagesAccording to Bjarne Stroustrup, author of the C++

    programming language, for a language to callitself object-oriented, it must support threeconcepts: objects, classes, and inheritance.

    1. Fully Object Oriented Language:-.Net,Java.

    2. Partially Object Oriented Language:-C++

    3. Object based Language:- Vb6.0

  • 8/9/2019 OOPs CSharp

    6/43

    Class and ObjectsWe can think of a class as simply a type (just

    like char, int, or long) that has methodsassociated with it .

    Object is an instance of a type or class.

    A class is a blueprint for a given set offunctionality, and an object created

    based on a particular class has all thefunctionality of the class built right in.Instances of classes are called as Objects. They might

    represent individual employees if Employee is defined asa Class..

  • 8/9/2019 OOPs CSharp

    7/43

    Three Pillars of OOPs Encapsulation

    Inheritance

    Polymorphism

  • 8/9/2019 OOPs CSharp

    8/43

    EncapsulationEncapsulation is process of keeping data

    and methods together inside objects.

    encapsulation is realized through the

    classes. A Class can contain data andmethods.

    Lke Employee class will provide properties(Name,Age ....) as well as actions(Calculatesalary, GoonLeave....) of theemployee entity.

    Instances of classes are called as Objects. They mightrepresent individual employees.

  • 8/9/2019 OOPs CSharp

    9/43

  • 8/9/2019 OOPs CSharp

    10/43

    Function OverloadingFunction overloadingallows the existence of

    multiple functions with the same name,

    differing only in the parameters.

    For example, if you were creating a method to printa data, you might declare several functions, eachnamed Write.

    One version would accept a string as a parameter;another, an integer; and yet another, a

    DateTime,object.But Overloading allows to define many functionhaving different parameters but still the samename.

  • 8/9/2019 OOPs CSharp

    11/43

    class Salary

    {

    int basic, comm, deduct, ta, ha =0;

    public void getnetsal(int b,int c,int d)

    {

    Console.WriteLine(b+c-d);

    }

    public void getnetsal(int b, int c, int d,int t,int h)

    {

    Console.WriteLine(b + c + t + h - d);

    }

    }

  • 8/9/2019 OOPs CSharp

    12/43

    PropertiesProperties are such members of classes,

    structs or interfaces that provide a flexiblemechanism to read, write, or compute the

    values of private fields through accessors.

    Unlike fields, properties do not designate storagelocations. Instead, properties have accessorsthat read, write, or compute their values.

    [modifiers] type identifier{accessor-declaration}

  • 8/9/2019 OOPs CSharp

    13/43

    Class transaction { string acc_id; int dipos,withd,bal; private string acc_no //read and write

    { set { acc_id=value; }

    get { return(acc_id); } }

    private int balance //read only {

    get { return(bal); }

    }

    private int withdraw //write only { set { withd=value; bal-=withd; }

    }

    }

  • 8/9/2019 OOPs CSharp

    14/43

    Constructor and DestructorConstructor is special function that is called automatically

    whenever new instance is created.

    It is used to initialize the values for class data member.

    There can be any number of constructors in a program butmust be differ in terms of their parameters, Called asOverloaded constructor.

    Destructor is such special function that is invokedautomatically when an instance is destroyed.

    Note :- The name of Constructor and Destructor must be the samename as Class name where both never return any value.

    Constructor can take one or more parameters but destructor can not.

    Destructor starts with (~) titles character.

  • 8/9/2019 OOPs CSharp

    15/43

    Account() //Default { }

    Account(int ac_no,string nm,) //Overloaded { }

    Account(int ac_no,string nm,int bal) //Overloaded { }

    ~Account() //Destructor { }

  • 8/9/2019 OOPs CSharp

    16/43

    ObjectsObject is an instance of a type or

    class.

    Instances of classes are called as Objects.

    For example there might be three instances of theEmployee - Ram , Raj and Tom.

    They might represent individual employees.

  • 8/9/2019 OOPs CSharp

    17/43

    Employees Ram=new Employee();

    Or Employee Raj;

    Raj=new Employee(); Or Customer abc=new

    customer(101,hyd); //CallingOverloaded constructor

  • 8/9/2019 OOPs CSharp

    18/43

    InheritanceInheritance relates to the programmer's ability to

    specify that one class has a kind-of relationshipwith another class. Through inheritance, you cancreate (or derive) a new class that's based on an

    existing class.In a few words, Inheritance is the process of

    creation new classes from already existingclasses.

    inheritance feature allows us to reuse some parts ofcode .

    The .NET framework has many baseclasses. Everything is derived fromSystem.Object .

  • 8/9/2019 OOPs CSharp

    19/43

    Class class1 {.}Class class2 : class1 {.}

    class class1

    {

    public int i; }

    class class2 : class1 { private void f1()

    { i = 10; } }

  • 8/9/2019 OOPs CSharp

    20/43

    Types OfInheritance1. Singe Level or Single Inheritance

    2. Multilevel Inheritance

    3. Multiple Inheritance4. Hierarchical Inheritance

    5. Hybrid Inheritance

  • 8/9/2019 OOPs CSharp

    21/43

    Base Class

    Child Class

    Single Level Multi level

    Base Class

    Child Class

    Grand Child

    Multiple

    Class1

    Class12

    Class2

  • 8/9/2019 OOPs CSharp

    22/43

    .

    Hybrid

    Base Class

    Child1 Child2

    Child11

    Base Class

    Child1 Child2

    Child12

    Hierarchical

    Multiple

    Multiple Inheritance is not supported by in .Net.

    Hierarchical

  • 8/9/2019 OOPs CSharp

    23/43

    Multiple inheritanceMultiple inheritance is the possibility that a child

    class can have multiple parents. Human beingshave always two parents, so a child will havecharacteristics from both parents.

    In OOP, multiple inheritance might become difficultto handle because it allows ambiguity for thecompiler. There are programming languagessuch as C++ that allow multiple inheritance;however, other programming languages such asJava and the .NET Framework languages do not

    allow multiple inheritance. Multiple inheritancecan be emulated in .NET using Multiple InterfaceInheritance .

  • 8/9/2019 OOPs CSharp

    24/43

    Access Modifiersprivate Access limited to the containing type.

    protectedAccess limited to the containing class or types

    derived from the containing class.

    internal Access limited to this program.

    Protected internal Access limited to this program or

    types derived from the containing class outside theprogram.

    public Access not limited.

    ***Bydefault All members(data & function) will be Private.

  • 8/9/2019 OOPs CSharp

    25/43

    Sealed classSome object model designs need to allow the

    creation of new instances but not inheritance, ifthis is the case, the class should be declared assealed.

    A sealed class is a class that does not allowinheritance.

    To create a sealed class in C# :-

    sealed class Shape

    To create a sealed class in VB.NET, :

    NonInheritable Class Shape

  • 8/9/2019 OOPs CSharp

    26/43

    AbstractionAbstraction is "the process of identifying common

    patterns that have systematic variations; anabstraction represents the common pattern andprovides a means for specifying which variation

    to use" .Great example is a bank account. People own

    savings accounts, checking accounts, creditaccounts, investment accounts, but not genericbank accounts.

    In this case, a bank account can be an abstract

    class and all the other specialized bank accountsinherit from bank account.

  • 8/9/2019 OOPs CSharp

    27/43

    An abstract class is a parent class thatallows inheritance but can never be

    instantiated.Abstract classes contain one or more

    abstract methods that do not haveimplementation. Abstract classes

    allow specialization of inheritedclasses.

  • 8/9/2019 OOPs CSharp

    28/43

    To create an abstract class in C# :-

    abstract class Shape

    To create an abstract class in VB.NET,

    MustInherit Class Shape

  • 8/9/2019 OOPs CSharp

    29/43

    abstract class Vehicle { public float weight; public byte tyre;

    public abstract string start(); //abstract function

    public void stop() //unabstract function { Console.WriteLine("Vehicle Stoped"); }

    }

    Note :- An abstract class can have zero or more abstract as well asunabstract function.

    But an abstract function can only be declared inside Abstarct class. But abstract function does not have body part but only declration. The abstarct function must be public.

  • 8/9/2019 OOPs CSharp

    30/43

    class car :Vehicle

    {

    public override string start()

    {

    return("started");

    }

    Note :- If a child class inherits from a abstract class , thechild class has to define the body of all abstract functionexisting into base class using override keyword.

  • 8/9/2019 OOPs CSharp

    31/43

    Virtual keywordA virtual property or method has an implementation in the

    base class, and can be overriden in the derived classes.The virtual keyword allows polymorphism too.

    To create a virtual member in C#:-

    public virtual void Draw() {-------} --Base class MemberPublic override void Draw(){-----} Child class

    To create a virtual member in VB.NET :-

    Public Overridable Function Draw()

  • 8/9/2019 OOPs CSharp

    32/43

    class clas3 { public virtual void vf() { } Public void f1()

    { } }

    class cls4 : clas3 { public override void vf() { }

    Public void new f1() { } }

  • 8/9/2019 OOPs CSharp

    33/43

    Override keywordOverriding is the action of modifying or

    replacing the implementation of theparent class with a new one.

    Parent classes with virtualvirtual oror abstractabstractmembers (in Abstract class) allowderived classes to override them.

    To override a member in C# :-

    public override void CalculateArea() To override a member in VB.NET :-Public Overrides Function CalculateArea()

  • 8/9/2019 OOPs CSharp

    34/43

  • 8/9/2019 OOPs CSharp

    35/43

    interface Iface

    {

    void send(string msg); string get();

    }

    Note :-Interface Members are by default Public.A field can not be defined within an Interface.

  • 8/9/2019 OOPs CSharp

    36/43

    class Msg : Iface { string message; public void send(string msg) {

    message=msg; }

    public string get() { return(message);

    } }Note :- A class can Implement any number ofInterfaces.

    class Msg : Iface,Iface2 { ------- }The class has to implement all of the members declared into Iface and Iface2.

  • 8/9/2019 OOPs CSharp

    37/43

    Avoiding Name Ambiguity

    interface Interdemo{ void Show();}interface Interdemo1{ void Show();}

    class Interclash:Interdemo,Interdemo1{ void Interdemo.Show() {

    Console.WriteLine("Show() method Implemented"); }void Interdemo1.Show() {

    Console.WriteLine("Display() method Implemented"); }

    To call the members :-

    Interclash inter = new Interclash();inter.Interdemo.Show();

    inter.Interdemo1.Show(); }

  • 8/9/2019 OOPs CSharp

    38/43

    Why Use Interfaces?

    To allow a class to inherit multiplebehaviors from multiple interfaces.

    To avoid name ambiguity between the

    methods of the different classes aswas in the use of multiple inheritancein C++.

    To combine two or more interfaces

    such that a class need only implementthe combined result.

  • 8/9/2019 OOPs CSharp

    39/43

    Note constructor also inherits base class constructor. To override already defined method (into base class ) into child class a

    keyword new is used. A virtual function can have body in base class but a abstract function

    can never have body in base class. A virtual function can reside in abstract class as well as unabstract

    class also. A abstract function can only be appear in abstract class. A abstract class can have abstract as well as unabstract function also. A virtual and abstract both type of function can be overidden in child

    class using override keyword.

    An Object can not be created for Abstract classes or Interfaces.

    Interface can not contain any field (variable).

    An abstract can contain field and unabstract functions also butInterface can contain only abstract functions.

    An Interface can be defined within a class also.

  • 8/9/2019 OOPs CSharp

    40/43

    Operator OverloadingOperator is used to defined, what function need to perform with the

    Operands.

    Like res= num1 + 100;

    The Operator Overloading is a way to redefine the functionalityOf an existing Operator.

    This gives the operator more than one meaning, or "overloads" it. Thecompiler distinguishes between the different meanings of anoperator by examining the types of its operands.

    You can redefine the function of most built-in operators globally or ona class-by-class basis. Overloaded operators are implemented asfunctions.

  • 8/9/2019 OOPs CSharp

    41/43

    Example class op_cls { int num1;

    public op_cls() { num1=0; }

    public op_cls(int arg) { num1=arg; }

    public static op_cls operator +(op_cls obj1,op_cls obj2) { op_cls obj3=new op_cls();

    obj3.num1=obj1.num1+obj2.num1;

    return(obj3); }

    public void show() { Console.WriteLine(num1.ToString()); }

    }

  • 8/9/2019 OOPs CSharp

    42/43

    Using Overloaded Operator op_cls o1=new op_cls(100);

    op_cls o2=new 0p_cls(200);

    op_cls o3=new op_cls();

    o3=o1+o2;

    o3.show(); //300

  • 8/9/2019 OOPs CSharp

    43/43

    Overloadable Operators

    +, -, !, ~, ++, --,true, false

    +, -, *,/, %, &, |, ^,

    =, ., ?:, ->, new, is,sizeof, typeof

    These unaryoperators can beoverloaded.

    These binaryoperators can beoverloaded.

    These operators

    cannot beoverloaded.