4.OOP With CSharp

Embed Size (px)

Citation preview

  • 8/13/2019 4.OOP With CSharp

    1/45

    1

    OOP with C#

    Chapter - 4

  • 8/13/2019 4.OOP With CSharp

    2/45

    2

    Objectives

    Basic Class in C# Visibility

    Encapsulation

     Accessor (get) and Mutator (set) Named Property

    Inheritance

    Sealed classes

    Polymorphism

     Abstract Class and Method

  • 8/13/2019 4.OOP With CSharp

    3/45

    3

    C# Classes

     A Class is a custom User Defined Type(UDT)

     A Class consists of data (attributes) and

    functions (methods) Example: To model a generic

    Employee, we can define an Employee

    Class

  • 8/13/2019 4.OOP With CSharp

    4/45

    4

    Employee Class

    Employee

    attributes:

    string fullname;int empID;float currPay;

    methods:

    void GiveBonus(float amount);void DisplayStats();

  • 8/13/2019 4.OOP With CSharp

    5/45

    5

    Source Codeusing System;

    namespace Employee{ 

    public class Employee

    {

    // private data

    private string fullName;

    private int empID;

    private float currPay;

    // Default ctor.

    public Employee(){ }

    // Custom ctor

    public Employee(string fullName, int empID, float currPay)

    {

    // Assign internal state data. Note use of 'this' keywordthis.fullName = fullName;

    this.empID = empID;

    this.currPay = currPay;

    }

  • 8/13/2019 4.OOP With CSharp

    6/45

    6

    Source Code (Contd…) // Bump the pay for this emp.

    public void GiveBonus(float amount){currPay += amount;}

    // Show the state

    public void DisplayStats()

    {

    Console.WriteLine("Name: {0}", fullName);

    Console.WriteLine("Pay: {0}", currPay);

    Console.WriteLine("ID: {0}", empID);

    }

    public static void Main(string[ ] args)

    {

    Employee e = new Employee("Joe",111,23987.50F);

    e.GiveBonus(200);e.DisplayStats();

    }

    }

    }

  • 8/13/2019 4.OOP With CSharp

    7/45

    7

    Method Overloading and 'th is '

    Overloading of Methods is same as C++.Constructors can be overloaded.

    For method resolution, return type alone is notnecessary!

    Is the keyword 'this' always necessary?

    Yes, if the parameter name and the class membername are same. Otherwise No!

    Static member functions can't use 'this' keyword.Why?

    The keyword 'this' can also be used to force oneconstructor to call another during the object creation

    Ex: public Employee(string fullName) : this(fullName,GetEmpId(), currPay) { }

  • 8/13/2019 4.OOP With CSharp

    8/45

    8

    Default public interface

    Declared in the class using publickeyword

    It includes members-

    Methods Properties

    Constants/read-only fields

  • 8/13/2019 4.OOP With CSharp

    9/45

    9

    Basic OOP Concepts

    Encapsulation Hiding unnecessary implementation details

    Inheritance "is-a" and "has-a" relationship

    "is-a" means sub-classes or derived classes "has-a" means containment or delegation

    Polymorphism It is the ability of the language to treat related

    objects the same way When sub-classes override the behavior defined by

    base a class, they are essentially redefining howthey respond to the same message

  • 8/13/2019 4.OOP With CSharp

    10/45

    10

    Examples

    EncapsulationDBReader f = new DBReader(); // details are hidden

    f.Open("@C:\foo.mdf");

    // process the database file

    f.Close();

    Inheritance

    Polymorphism

    is-a Relationship

    Object

    Shape

    Hexagon

    has-a Relationship

    Car

    Radio

    Shapevoid Draw( )

    Hexagon Circle

    Draw() Draw()

  • 8/13/2019 4.OOP With CSharp

    11/45

    11

    More Details: (1) Encapsulation

    The main objective of encapsulation is: theobject's instance should be allowed to accessthe internal member data directly. It alsoprovides the integrity of state data. How to dothis?

    Using private, public, protected, andprotected internal keywords

    To manipulate the private data, C# provides

    two methods: Define traditional accessor and mutator methods

    Define a named property

  • 8/13/2019 4.OOP With CSharp

    12/45

    12

    ncapsu a on us ng ra onaAccessors & Mutators

     Accessorclass Employee

    {

    private string fullName;

    public string GetName() { return fullName; }

    ………….. 

    } Mutator

    class Employee

    {

    private string fullName;

    public string SetName(string n){ fullName = n; }

    ……………. 

    }

  • 8/13/2019 4.OOP With CSharp

    13/45

    13

    Class Properties

    You can define a named property to avoidusing two different get  and set  methods

    The property is a single named field whichwraps the private data. These property

    names can then be used in Main( ). Ex: Assume EmpID is the name of the property

    public static void Main()

    {

    Employee e = new Employee();e.EmpID = 121; // set

    Console.WriteLine(e.EmpID); // get

    }

  • 8/13/2019 4.OOP With CSharp

    14/45

    14

    C# get  and set Methods

    using System;namespace get_set

    {

    class MyClass

    {

    private int a;

    public int A  // property {

    get  // accessor

    {

    return a;

    }

    set  // mutator{

    a = value;

    }

    }

    }

    class Class1{

    static void Main(string[] args)

    {

    MyClass obj = new MyClass();

    obj.A = 20;Console.WriteLine(obj.A);

    }

    }

    }

    get block – accessor set block – mutator  A  – named property

  • 8/13/2019 4.OOP With CSharp

    15/45

    15

    Read-Only and Write-Only Properties

    The named property A in the previous slidewas able to read and write. How to restrict the

    access of A as R/W?

    For Read-Only: simply define a property

    without a set block

    For write-only: simply define a property

    without a get block

    Ex: public float Pay public float Pay{ {

    get { return currPay; } set { currPay = value; }

    } }

  • 8/13/2019 4.OOP With CSharp

    16/45

    16

    stat ic : properties and constructors

    The static keyword can be used for propertiesalso

    The only difference is that, now theseproperties are bound to a class and not to aninstance

    Ex: Employee.EmpID = 111; Can a constructor be declared as static?

    Yes, but it is strange! Why? Because,constructors are executed during object

    creation Static constructors are used to initialize static

    data

  • 8/13/2019 4.OOP With CSharp

    17/45

    17

    Example – static property

    public class Employee

    {private static string companyName;

    public static string Company

    {

    get { return companyName; }

    set {companyName = value; }}

    }

    public static void Main(string[ ] args)

    {

    Employee.Company = "Microsoft";Console.WriteLine("The name is {0}", Employee. Company);

    }

  • 8/13/2019 4.OOP With CSharp

    18/45

  • 8/13/2019 4.OOP With CSharp

    19/45

    19

    Read-Only Fields

    Read-Only properties provide data preservation: keyword

    to be used is: "readonly "

    Ex: public readonly int rofield;

    You can't assign any value to the readonly  fields, exceptin a constructor

    Ex: void SomeMethod(){ rofield = 123; } // Error

    Static readonly  fields can also be used. It is useful toassociate many constant values bound to a class.

    It may be look similar to 'const' declaration. The

    difference, however, is that const  is resolved at compile-time and static readonly is resolved at run-time.

    The other context in which it is valid to pass a readonly  field as an out or ref  parameter.

  • 8/13/2019 4.OOP With CSharp

    20/45

    20

    More Details: (2) Inheritance

    Inheritance facilitates code reuse Inheritance provides dependency

    between types

    Inheritance comes in two flavors: "is-a" relationship

    "has-a" relationship

    Let us start with "is-a" relationship…… 

    Employee

    Manager

    SalesPerson

  • 8/13/2019 4.OOP With CSharp

    21/45

    21

    Manager – Derived Class

    public class Employee {……} using System;

    public class Manager : Employee

    {

    private ulong numberOfOptions;public ulong NumberOpts

    {

    get { return numberOfOptions; }

    set { numberOfOptions = value; }}

    }

  • 8/13/2019 4.OOP With CSharp

    22/45

    22

    SalesPerson – Derived Class

    using System;

    public class SalesPerson : Employee

    {

    private int numerOfSales;

    public int NumbSales{

    get { return numerOfSales; }

    set { numerOfSales = value; }}

    }

  • 8/13/2019 4.OOP With CSharp

    23/45

  • 8/13/2019 4.OOP With CSharp

    24/45

  • 8/13/2019 4.OOP With CSharp

    25/45

    25

    Accessibility constraints

    Constraints are

    1. Direct base class of a derived class must be at least as accessible as thederived class itself

    2. Accessibility domain of a member is never larger than that of the classcontaining it

    3. Return type of method must be at least as accessible as the methods itself

    Eg for 2&3.

    class A{….  }public class B{ A method1() { }Internal A method2() { }

    Public A method3() // Error}• All methods in B specify Aas their return types•method3 is error becausean accessibility level higherthan that of its return type 

    Eg for 1.a.

    class A{….} public class B:A{ … }  // is illegal A is internal by defaultEg 1.b. class A

    {…. private class B{ public int x; }}

     // public data x is not accessible outsidethe class B. because B is private the xreduced to private

  • 8/13/2019 4.OOP With CSharp

    26/45

    26

    Base class and Subclass Constructors

    When a derived class object is createdan appropriate constructor for derived

    class is created

     A subclass constructor automaticallycalls the base class constructor, by

    default

    For that derived class uses the base keyword

  • 8/13/2019 4.OOP With CSharp

    27/45

    27

    Example

    using System

    Class Room{ public int length, breadth;

    public Room(int x, int y)

    { length = x; breadth=y; }

    public int Area()

    { return (length * breadth); }}

    Class Lroom:Room

    { int height;

    public Lroom(int x, int y, intz) : base(x,y)

    { height = z; }

    public int volume()

    { return(length * breadth * height); }

    }

  • 8/13/2019 4.OOP With CSharp

    28/45

    28

    Contd..

    Class InherTest{ public static void Main()

    { Lroom r1=new Lroom(14,12,10);

    int area1 = r1.Area()int volume1=r1.volume();

    Console.WriteLine(“Area = “+area1); 

    Console.WriteLine(“Volume = “+volume1); }}

  • 8/13/2019 4.OOP With CSharp

    29/45

    29

    Multilevel inheritance

    The chain ABC is known as inheritance path.

    The constructor are created from the top downwards

    Eg .

    class A

    {….} 

    class B:A{ … } class C:B

    { ….. } 

     A

    B

    C

  • 8/13/2019 4.OOP With CSharp

    30/45

    30

    More features of "is-a"

    Multiple Inheritance In C#, a given class can have exactly one direct

    base class

    It is not permitted to have a single type with one ormore base classes

    "protected " Keyword You know that a private member can't be

    accessed by even subclasses

    " protected " data or methods can be accessed bysubclasses

    Sealed Classes If you want to design a class that can't be

    inherited, then use the keyword: "sealed "

     A sealed class cannot also be an abstract class.It also enables certain run-time optimizations

  • 8/13/2019 4.OOP With CSharp

    31/45

    31

    Example – Sealed Classes

     Add a subclass PTSalesPerson forSalesPerson class to have part – time salespeople.

    Since we can't think of more child classesunder PTSalesPerson, we shall seal  it

    Sealed classes are most useful for designingstandalone classes. Ex: String class in the

    System namespace Example

    public sealed PTSalesPerson : SalesPerson

    { ………. } 

    EmployeeManager

    SalesPerson PTSalesPerson

    C t i t/D l ti

  • 8/13/2019 4.OOP With CSharp

    32/45

    32

    Containment/Delegation

    or has-a  relationship Let us consider two classes: A Car class and a Radio class

    It is odd to think of Radio is a Car! Instead, we can say a Car has a Radio

    Car – is called as Containing ClassRadio – is called as Contained Class

    To expose the functionality of the inner class to the outside worldrequires delegation

    Delegation means adding members to the containing class that makeuse of the contained class's functionality

    Eg: Class A

    { …. } Class B

    { ….  A a; // A is contained in B

    }

    B b;

    …….. 

  • 8/13/2019 4.OOP With CSharp

    33/45

    33

    More Details: (3) Polymorphism

    Polymorphism is the ability for classes to provide

    different implementations of methods that arecalled by the same name.

    For Example, assume that you have added a newmethod to Employee class as:

    public void GiveBonus(float amount){ currPay += amount; }

    This method is common for all objects derived fromEmployee. However, our objective is to design thisto behave differently for Manager and

    SalesPerson. This means that the subclasses should be able to

    provide different interfaces to Employee class

    Polymorphism is achieved through " virtual " and "

    override " keywords

  • 8/13/2019 4.OOP With CSharp

    34/45

    34

    Types of Polymorphism

    Interface polymorphism - Multiple classes may

    implement the same interface, and a single classmay implement one or more interfaces. Interfaces areessentially definitions of how a class needs torespond. An interface describes the methods,properties, and events that a class needs to

    implement. Inheritance polymorphism - Multiple classes may

    inherit  from a single base class. By inheriting, a classreceives all of the methods, properties, and events ofthe base class in the same implementation as thebase class.

    Polymorphism through abstract classes - Abstractclasses provide elements of both inheritance andinterfaces. An abstract class is a class that cannot beinstantiated itself; it must be inherited.

  • 8/13/2019 4.OOP With CSharp

    35/45

    35

    Base Claass

    Examplepublic class Employee

    {public virtual void GiveBonus(float amount)

    { currPay += amount; }

    ……… }

    public class SalesPerson : Employee

    {public override void GiveBonus(float amount)

    {

    int salesBonus = 0;

    if (numberOfSales > 200)

    salesBonus = 1000;

    base.GiveBonus(amount + salesBonus);}

    }

     You can reuse the base class method by using the keyword base

  • 8/13/2019 4.OOP With CSharp

    36/45

    36

    Abstract Classes

     An abstract  class cannot be instantiateddirectly, and it is a compile-time error to use

    the new  operator on an abstract class

     An abstract class is permitted (but not

    required) to contain abstract members  An abstract class cannot be sealed.

    Ex: If the Employee class is declared as

    abstract, the the following stmt. gives an error:Employee e = new Employee();

  • 8/13/2019 4.OOP With CSharp

    37/45

    37

    Contd..

    Characteristics-  it cannot be instantiated directly

    It can have abstract members

    Cannot apply a sealed modifier to it

  • 8/13/2019 4.OOP With CSharp

    38/45

    38

    Abstract Methods

    When an instance method declarationincludes the modifier abstract, it is called

    abstract method

    It is implicitly virtual method & does notprovide implementation

    Ex: public abstract void Draw(int x, int y);

    It ends with semicolon 

  • 8/13/2019 4.OOP With CSharp

    39/45

    39

    Contd..

    Characteristics-  it cannot have implementation

    Its implementation must be provided

    in non-abstract derived classes byoverriding the method

    It can only be declared in abstract

    classes

    It cannot take static or virtual modifier

  • 8/13/2019 4.OOP With CSharp

    40/45

    40

    Method Hiding

    The base class method with virtual &the subclass method with thekeyword override, resulted in „hiding‟the base class method from subclass

    How to override a method withoutdeclaring it virtual?

    Solution is – use of new modifier

    Modifier new tell the compiler that thederived class method „hides‟ the baseclass method

  • 8/13/2019 4.OOP With CSharp

    41/45

    41

    Example

    Using system;

    Class Base{ public void Display( )

    { CW(“Base method”);} }

    Class Derived:Base

    { public new void Display( )

    { CW (“Derived Method”);} }

    Class Test

    { public static void Main()

    { Derived d= new Derived();

    d.Display(); }

    }

  • 8/13/2019 4.OOP With CSharp

    42/45

    42

    Method Hiding

    Method hiding is opposite of Method overriding

     Assume that Oval is-a type of Circle. Of course you candefine a method Draw() which overrides Draw() of its parentclass and provide its own versioning.

    However, if we want to prevent the Oval class from inheritingany previous logic, use "new " keyword

    public class Oval : Circle{

    public Oval(){base.PetName = "Joe";}

    // Hide base class impl if they create an Oval.

    new public void Draw()

    {

    Console.WriteLine("Oval with class versioning");}

    }

      new  keyword breaks the relationship between baseclass of abstract Draw() and the derived class version

  • 8/13/2019 4.OOP With CSharp

    43/45

    43

    new  Modifier

    // The new modifier

    using System;public class MyBaseC

    {

    public static int x = 55;

    public static int y = 22;

    }

    public class MyDerivedC : MyBaseC

    {

    new public static int x = 100; // Name hiding

    public static void Main( )

    {Console.WriteLine(x); // Display the overlapping value of x:

    Console.WriteLine(MyBaseC.x); // Access the hidden value of x:

    Console.WriteLine(y); // Display the unhidden member y:

    }

    }

    Output:1005522

  • 8/13/2019 4.OOP With CSharp

    44/45

    44

    Shape Class – Design overview

    The subclass Circle does not override Draw(), whereasHexagon does

    Refer to Shapes Project

    public abstract class Shape{

    public virtual void Draw(){ … } 

    }

    public class Circle : Shape

    { … } 

    public class Hexagon : Shape{

    public override void Draw(){ ... }}

    It is moreintelligent to

    declareDraw() as

    abstract

    Same aspure

    virtualfunction of

    C++

    http://localhost/var/www/apps/conversion/tmp/scratch_3/Shapes/Shapes.csprojhttp://localhost/var/www/apps/conversion/tmp/scratch_3/Shapes/Shapes.csproj

  • 8/13/2019 4.OOP With CSharp

    45/45

    End of Chapter