opps piller in c#

Upload: deepak-harbola

Post on 06-Apr-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 opps piller in c#

    1/47

    A class is nothing more than a custom user- definedtype (UDT)That is composed of-field data (sometimes termed member variables)

    and-functions (often called methods in OO speak) thatact on this data.

    The set of field data collectively represents thestate ofa class instance.

  • 8/2/2019 opps piller in c#

    2/47

  • 8/2/2019 opps piller in c#

    3/47

    public class Employee{...// Overloaded constructors.

    public Employee(){ }public Employee(string fullName, int empID, floatcurrPay){...}...

    }

  • 8/2/2019 opps piller in c#

    4/47

    public class Triangle{// The overloaded Draw() method.public void Draw(int x, int y, int height, int width) {...}

    public void Draw(float x, float y, float height, floatwidth) {...}public void Draw(Point upperLeft, Point bottomRight){...}

    public void Draw(Rect r) {...}}

  • 8/2/2019 opps piller in c#

    5/47

    public class Triangle{...// Error! Cannot overload methods

    // based solely on return values!public float GetX() {...}public int GetX() {...}}

  • 8/2/2019 opps piller in c#

    6/47

    // Explicitly use "this" to resolve name-clash.public Employee(string fullName, int empID, floatcurrPay){

    // Assign the incoming params to my state data.this.fullName = fullName;this.empID = empID;this.currPay = currPay;

    }

  • 8/2/2019 opps piller in c#

    7/47

    // When there is no name clash, "this" is assumed.public Employee(string name, int id, float pay){fullName = name;

    empID = id;currPay = pay;}

  • 8/2/2019 opps piller in c#

    8/47

    Public interface is any item declared in a class usingthe public keyword.

    Public interface of a class may be populatedby numerous members, including the following:

    Methods: Named units of work that model somebehavior of a class Properties: Traditional accessor and mutator

    functions in disguise Constants/Read-only fields: Field data that cannotbe changed after assignment

  • 8/2/2019 opps piller in c#

    9/47

    All object-oriented languages contend with three coreprinciples of object-oriented programming,often called the famed pillars of OOP.

    Encapsulation: How does this language hide anobjects internal implementation? Inheritance: How does this language promote codereuse?

    Polymorphism: How does this language let you treatrelated objects in a similar way?

  • 8/2/2019 opps piller in c#

    10/47

    Languages ability to hide unnecessary implementationdetails from the object user.

    For examplewe are using a class named DatabaseReader that has two

    methods named Open() and Close():

    // DatabaseReader encapsulates the details of databasemanipulation.

    DatabaseReader dbObj = new DatabaseReader();dbObj.Open(@"C:\Employees.mdf");// Do something with database...dbObj.Close();

  • 8/2/2019 opps piller in c#

    11/47

    DatabaseReader class has encapsulated the innerdetails ofLocatingloading,

    ManipulatingAnd closing the data file.

  • 8/2/2019 opps piller in c#

    12/47

    The concept of encapsulation revolves around thenotion that an objects field data should not bedirectly accessible from the public interface.

    if an object user wishes to alter the state of anobject, it does so indirectly using accessor (get) andmutator (set) methods

    In C#, encapsulation isenforced at the syntactic level using the public,private, protected, and protected internal.

  • 8/2/2019 opps piller in c#

    13/47

    namespace Employees

    {

    public class Employee

    {

    // Field data.

    private string fullName;private int empID;

    private float currPay;

    // Constructors.

    public Employee(){ }

    public Employee(string fullName, int

    empID, float currPay){

    this.fullName = fullName;

    this.empID = empID;

    this.currPay = currPay;

    }

    // Bump the pay for this employee.

    public void GiveBonus(float amount)

    { currPay += amount; }

    // Show current state of this object.

    public void DisplayStats()

    {Console.WriteLine("Name: {0} ",

    fullName);

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

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

    }

    }}

  • 8/2/2019 opps piller in c#

    14/47

    If we want the outside world to interact with our privatefullName data field, tradition dictates defining an accessor(get method) and mutator (set method).

    // Traditional accessor and mutatorfor a point of private data.

    public class Employee

    {

    private string fullName;

    ...

    // Accessor.public string GetFullName()

    {

    return fullName;

    }

    // Mutatorpublic void SetFullName(string n)

    {

    // Remove any illegal characters (!, @, #,

    $, %),

    // check maximum length (or case rules)

    before making assignment.fullName = n;

    }

    }

  • 8/2/2019 opps piller in c#

    15/47

    // Accessor/mutator usage.

    static void Main(string[] args)

    {

    Employee p = new Employee();

    p.SetFullName("Fred Flintstone");

    Console.WriteLine("Employee is named: {0}", p.GetFullName());Console.ReadLine();

    }

  • 8/2/2019 opps piller in c#

    16/47

    .NET languages prefer to enforce encapsulationusingproperties, which simulate publicly accessible points ofdata. Rather than requiring the user to call two differentmethods to get and set the state data, the user is able to callwhat appears to be a public field.

  • 8/2/2019 opps piller in c#

    17/47

    Ex We provided a property named ID that wraps theinternal empID member variable of the Employee type

    // Setting / getting a person's ID through property syntax.

    static void Main(string[] args){

    Employee p = new Employee();

    // Set the value.

    p.ID = 81;

    // Get the value.

    Console.WriteLine("Person ID is: {0} ", p.ID);Console.ReadLine();

    }}

  • 8/2/2019 opps piller in c#

    18/47

    // Encapsulation with properties.

    public class Employee

    {

    ...

    private int empID;

    private float currPay;

    private string fullName;

    // Property for empID.

    public int ID

    {

    get { return empID;}

    Set

    {// You are still free to investigate (and

    possibly transform)

    // the incoming value before making an

    assignment.

    empID = value;

    }}

    // Property for fullName.

    public string Name

    {

    get {return fullName;}

    set {fullName = value;}

    }

    // Property for currPay.

    public float Pay

    {

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

    }

    }

  • 8/2/2019 opps piller in c#

    19/47

    A property is represented in CIL code

    using get_ and set_ prefixes

  • 8/2/2019 opps piller in c#

    20/47

    The visibility of get and set logic was solely controlled by theaccess modifer of the property declaration:// Object users can only get the value, however// derived types can set the value.

    public string SocialSecurityNumber{get { return empSSN; }protected set { empSSN = value;}}

    In this case, the set logic of SocialSecurityNumber can only becalled by the current class and derived classes and thereforecannot be called from an object instance.

  • 8/2/2019 opps piller in c#

    21/47

    When creating class types, you may wish to configure a read-only property. To do so, simply build a property without acorresponding set block.

    public class Employee{...// Now as a read-only property.

    public string SocialSecurityNumber { get { return empSSN; } }}

  • 8/2/2019 opps piller in c#

    22/47

    // Static properties must operate on static data!public class Employee{private static string companyName;public static string Company{get { return companyName; }set { companyName = value;}

    }...}

  • 8/2/2019 opps piller in c#

    23/47

    Static properties are manipulated in the same manner asstatic methods, as seen here:// Set and get the name of the company that employs thesepeople...public static int Main(string[] args){Employee.Company = "Intertech Training";Console.WriteLine("These folks work at {0} ",

    Employee.Company);...}

  • 8/2/2019 opps piller in c#

    24/47

    Inheritance is the aspect of OOP that facilitates codereuse.

    languages ability to allow you to build new classdefinitions based on existing class definitions

    inheritance allows you to extend the behavior of a

    base (orparent) class by enabling a subclass to inheritcore functionality (also calleda derived class or childclass).

  • 8/2/2019 opps piller in c#

    25/47

    Inheritance comes in two flavors:

    Classical inheritance(the is-a relationship)

    And the containment/delegation model

    (the has-a relationship).

  • 8/2/2019 opps piller in c#

    26/47

    The basic idea behind classical inheritance is that new classesmay leverage (and possibly extend) the functionality of otherclasses.

    Extend the functionality of the Employee class to create two

    new classes (SalesPerson and Manager).SalesPerson is-a Employee (as is a Manager)

  • 8/2/2019 opps piller in c#

    27/47

    Base classes (such as Employee) are used to definegeneral characteristics that are common to alldescendents. Subclasses (such as SalesPerson and

    Manager) extend this general functionality whileadding more specific behaviors.

    Extending a class is accomplished using the

    colon operator (:) on the class definition.

  • 8/2/2019 opps piller in c#

    28/47

    // Add two new subclasses to the

    Employees namespace.

    namespace Employees

    {

    public class Manager : Employee

    {// Managers need to know their number

    of stock options.

    private ulong numberOfOptions;

    public ulong NumbOpts

    {

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

    }

    }

    public class SalesPerson : Employee

    {

    // Salespeople need to know their

    number of sales.

    private int numberOfSales;

    public int NumbSales{

    get { return numberOfSales;}

    set { numberOfSales = value; }

    }

    }

    }

  • 8/2/2019 opps piller in c#

    29/47

    Having is-a

    relationship, SalesPersonand Manager have

    automatically

    inherited all public (andprotected) members of

    the Employee base class.

    // Create a subclass and access

    base class functionality.static void Main(string[] args)

    {

    // Make a salesperson.

    SalesPerson stan = new

    SalesPerson();

    // These members are inherited

    from the Employee base class.

    stan.ID = 100;

    stan.Name = "Stan";// This is defined by the

    SalesPerson class.

    stan.NumbSales = 42;

    Console.ReadLine();}

  • 8/2/2019 opps piller in c#

    30/47

    Base classes (such as Employee) are used to definegeneral characteristics that are common to alldescendents. Subclasses (such as SalesPerson and

    Manager) extend this general functionality whileadding more specific behaviors.

    Extending a class is accomplished using the

    colon operator (:) on the class definition.

  • 8/2/2019 opps piller in c#

    31/47

    static void Main(string[] args){// Assume we now have the following constructor.

    // (name, age, ID, pay, SSN, number of stockoptions).Manager John = new Manager(John", 35, 92,100000, "333-23-2322", 9000);

    }.

  • 8/2/2019 opps piller in c#

    32/47

    // If you do not say otherwise, a subclass constructorautomatically calls the default constructor of its base class.

    public Manager(string fullName, int age, int empID,float currPay, string ssn, ulong numbOfOpts){// This point of data belongs with us!

    numberOfOptions = numbOfOpts;

    // Leverage the various members inherited from Employee// to assign the state data.ID = empID;Age = age;Name = fullName;SocialSecurityNumber = ssn;Pay = currPay;}

  • 8/2/2019 opps piller in c#

    33/47

    // This time, use the C# "base" keyword to call acustom// constructor on the base class.

    public Manager(string fullName, int age, int empID,float currPay,string ssn, ulong numbOfOpts): base(fullName, age, empID, currPay, ssn)

    {numberOfOptions = numbOfOpts;}

  • 8/2/2019 opps piller in c#

    34/47

    A class have exactly one direct base class. Therefore,it is not possible to have a single type with two ormore base classes.

    C# does allow a given type to implementany number of discrete interfaces

  • 8/2/2019 opps piller in c#

    35/47

    Public items are directly accessible from anywhere,while private items cannotbe accessed from any object beyond the class thathas defined it.

    Additional level of accessibility: protected.When a base class defines protected data or

    protected members, it is able to create a set ofitems that can be accessed directly by anydescendent

  • 8/2/2019 opps piller in c#

    36/47

    If we wish to allow the SalesPerson and Manager child classesto directly access the data sector defined by Employee weupdate code as following-

    // Protected state data.

    public class Employee{// Child classes can directly access this information. Objectusers cannot.protected string fullName;protected int empID;protected float currPay;protected string empSSN;protected int empAge;...}

  • 8/2/2019 opps piller in c#

    37/47

    static void Main(string[] args){// Error! Can't access protected data from object

    instance.Employee emp = new Employee();emp.empSSN = "111-11-1111";}

  • 8/2/2019 opps piller in c#

    38/47

    PTSalesPerson is a class representing (ofcourse) a part-time salesperson.

  • 8/2/2019 opps piller in c#

    39/47

    // Ensure that PTSalesPerson cannot act as a baseclass to others.public sealed class PTSalesPerson : SalesPerson{

    public PTSalesPerson(string fullName, int age, intempID, float currPay, string ssn, int numbOfSales): base(fullName, age, empID, currPay, ssn,numbOfSales)

    {}}.

  • 8/2/2019 opps piller in c#

    40/47

    // Compiler error!public class ReallyPTSalesPerson :PTSalesPerson{ ... }

  • 8/2/2019 opps piller in c#

    41/47

    The sealed keyword is most useful whencreating stand-alone utility classes.

    For Ex. String class defined in the System namespace

    has been explicitly sealed:public sealed class string : object,IComparable, ICloneable,

    IConvertible, IEnumerable {...}Therefore, you cannot create some new class derivingfrom System.String:

  • 8/2/2019 opps piller in c#

    42/47

    We Created a new class that models an employeebenefits package:

    // This type will function as a contained class.

    public class BenefitPackage{// Assume we have other members that represent// 401K plans, dental / health benefits and so on.public double ComputePayDeduction(){ return 125.0; }}Manager is-a BenefitPackage?Each employee has-a BenefitPackage.

  • 8/2/2019 opps piller in c#

    43/47

    // Employees now have benefits.public class Employee{...// Contain a BenefitPackage object.

    protected BenefitPackage empBenefits = newBenefitPackage();}.To expose the functionality of the contained object to the

    outside world requires delegation.Delegation is simply the act of adding members to thecontaining class that make use of the contained objectsfunctionality.

  • 8/2/2019 opps piller in c#

    44/47

    A type (enum, class, interface, struct, ordelegate) declared within a class or struct iscalled a nested type.

    Using System;class A{class B{

    static void F(){Console.WriteLine("A.B.F");}} }

  • 8/2/2019 opps piller in c#

    45/47

    using System;

    namespace Nested{class ContainerClass{

    class InnerClass

    { public string str = "A string variable in nested class";}

    public static void Main(){

    InnerClass nestedClassObj = new InnerClass();Console.WriteLine(nestedClassObj.str);

    }}

    }

  • 8/2/2019 opps piller in c#

    46/47

    Nested types can access private andProtected members of the containing type,

    including any inherited private or protectedmembers.

    using System;

  • 8/2/2019 opps piller in c#

    47/47

    using System;namespace Nested{class ContainerClass{

    string OuterClassVariable = "I am an outer class variable";public class InnerClass{ContainerClass ContainerClassObject = new ContainerClass();string InnerClassVariable = "I am an Inner class variable";

    public InnerClass(){Console.WriteLine(ContainerClassObject.OuterClassVariable);Console.WriteLine(this.InnerClassVariable);

    } } }

    class Demo{public static void Main(){ContainerClass.InnerClass nestedClassObj = new

    ContainerClass.InnerClass();} }}