开发者

Why should I use protected variables(members/property) with Inheritance? What are the advantages of using it?

I was going through code samples of Begining C# 3.0 and followed the sample code along.

When I have created a public/protected method then I was able to access that method using the object of derived class. Ex:

class clsBuilding
    {
    protected string address { get; set; }
    protected Decimal purchasePrice { get; set; }
    protected decimal monthlyPayment { get; set; }
    protected Decimal taxes { get; set; }
    protected decimal insurance { get; set; }
    protected DateTime datePurchased { get; set; }
    protected int buildingType { get; set; }


     public void PropertySummary(string[] desc)
        {
            desc[0] = "Property Type:  "+whichType[buildingType] +
                        "," + address +
                        ",Cost: " + purchasePrice.ToString("C")+
                        ", Monthly Payment:" + monthlyPayment.ToString("C");
            desc[1] = "Insurance: " + insurance.ToString("C") +
                        " Taxes:  " + taxes.ToString("C")+
                            "Date Purchased: " + datePurchased.ToShortDateString();
            desc[2] = "";
        }
..............
}

class clsApartment : clsBuilding
    {
      ........................
}
.......
myApt = new clsApartment();

myApt.PropertySummary(desc);

But what is the use of protected property that I have declared at the begining of the parent Class. When I was trying to access them either by using the object of the derived class or directly as instructed in the book:

Just to Drive the point home,given a line in clsBuilding(parent class):

protected decimal purchase price;

you could have the line :

you could have the line purchaseprice = 150000M ; in class home and it would be perfectly acceptable. (Chapter 15,page 447 after 4th paragraph) , neither was a successful on attempt.

I am sure , I must have got the concept wrong or missed something. If not then , why any one would be declaring protected variable or property?

EDIT:

public class clsBuilding
{
    //--------------------- Symbolic constants -------------------
    public const int APARTMENT = 1;
    public const int COMMERCIAL = 2;
    public const int HOME = 3;

    private string[] whichType = { "", "Apartment", "Commercial", "Home" };

    //--------------------- Instance variables -------------------
    protected string address;
    protected decimal purchasePrice;
    protected decimal monthlyPayment;
    protected decimal taxes;
    protected decimal insurance;
    protected DateTime datePurchased;
    protected int buildingType;
    //--------------------- Constructor --------------------------
    public clsBuilding()
    {
        address = "Not closed yet";
    }

    public clsBuilding(string addr, decimal price, decimal payment,
                       decimal tax, decimal insur, DateTime date, int type):this()
    {
        if (addr.Equals("") == false)
            address = addr;
        purchasePrice = price;
        monthlyPayment = 开发者_开发问答payment;
        taxes = tax;
        insurance = insur;
        datePurchased = date;
        buildingType = type;
    }
    //--------------------- Property Methods ---------------------

    public string Address
    {
        get
        {
            return address;
        }
        set
        {
            if (value.Length != 0)
                address = value;
        }
    }
    public decimal PurchasePrice
    {
        get
        {
            return purchasePrice;
        }
        set
        {
            if (value > 0M)
                purchasePrice = value;
        }
    }

    public decimal MonthlyPayment
    {
        get
        {
            return monthlyPayment;
        }
        set
        {
            if (value > 0M)
                monthlyPayment = value;
        }
    }

    public decimal Taxes
    {
        get
        {
            return taxes;
        }
        set
        {
            if (value > 0M)
                taxes = value;
        }
    }

    public decimal Insurance
    {
        get
        {
            return insurance;
        }
        set
        {
            if (value > 0M)
                insurance = value;
        }
    }

    public DateTime DatePurchased
    {
        get
        {
            return datePurchased;
        }
        set
        {
            if (value.Year > 2008)
                datePurchased = value;
        }
    }

    public int BuildingType
    {
        get
        {
            return buildingType;
        }
        set
        {
            if (value >= APARTMENT && value <= HOME)
                buildingType = value;
        }
    }
    //--------------------- General Methods ----------------------

    /*****
     * Purpose: Provide a basic description of the property
     * 
     * Parameter list:
     *  string[] desc       a string array to hold description
     *  
     * Return value:
     *  void
     *  
     * CAUTION: Method assumes that there are 3 elements in array
     ******/
    public void PropertySummary(string[] desc)
    {

        desc[0] = "Property type: " + whichType[buildingType] + 
                  ", " + address + 
                  ", Cost: " + purchasePrice.ToString("C") + 
                  ", Monthly payment: " + monthlyPayment.ToString("C");
        desc[1] = "     Insurance: " + insurance.ToString("C") + " Taxes: " + taxes.ToString("C") + 
                  "  Date purchased: " + datePurchased.ToShortDateString();
        desc[2] = " ";
    }

    /*****
     * Purpose: To call someone for snow removal, if available
     * 
     * Parameter list:
     *  n/a
     *  
     * Return value:
     *  string
     ******/
    public virtual string RemoveSnow()
    {
        return whichType[buildingType] + ": No snow removal service available.";
    }
}

class clsCommercial : clsBuilding
{
    //--------------------- Instance variables -------------------
    private int squareFeet;
    private int parkingSpaces;
    private decimal rentPerSquareFoot;

    //--------------------- Constructor --------------------------
    public clsCommercial(string addr, decimal price, decimal payment,
                        decimal tax, decimal insur, DateTime date, int type) :
                        base(addr, price, payment, tax, insur, date, type)
    {
        buildingType = type;   // Commercial type from base
    }
    //--------------------- Property Methods ---------------------
    public int SquareFeet
    {
        get
        {
            return squareFeet;
        }
        set
        {
            if (value > 0)
                squareFeet = value;
        }
    }
    public int ParkingSpaces
    {
        get
        {
            return parkingSpaces;
        }
        set
        {
            parkingSpaces = value;
        }
    }
    public decimal RentPerSquareFoot
    {
        get
        {
            return rentPerSquareFoot;
        }
        set
        {
            if (value > 0M)
                rentPerSquareFoot = value;
        }
    }

    //--------------------- General Methods ----------------------
    public override string RemoveSnow()
    {
        return "Commercial: Call Acme Snow Plowing: 803.234.5566";
    }

}


public frmMain()
    {
        InitializeComponent();
        myTime = DateTime.Now;

        myApt = new clsApartment("123 Ann Dotson Dr., Lexington, KY 40502", 550000, 6000,
                                             15000, 3400, myTime, 1);
        myComm = new clsCommercial("4442 Parker Place, York, SC 29745", 1200000, 9000,
                                        22000, 8000, myTime, 2);
        myHome = new clsHome("657 Dallas St, Ringgold, GA 30736", 260000, 1100,
                                    1750, 900, myTime, 3);
    }


A protected variable/property is accessible from the class and it's derived classes if I remember rightly.

Generally you would use one to prevent the property being publicly accessible to other classes which don't inherit from your class.


Building on what doug said. Protected makes a property, variable, or function available to a subclass, but not from outside the class. If you were to use private, it would still not be accessible from outside the class, nor would it be accessible from it's subclasses.


Protected members can be accessed by other members of the class just like private members. Protected members can also be accessed by members of derived classes. This is the sole difference between private and protected.

In this case the author of clsBuilding intended for the protected properties to be available to any derived classes. It is not a particularly good example without a concrete demonstration of a derived class. Perhaps the details of clsApartment that you omitted contain that demonstration – I certainly hope that is the case.


Here's an artificial example of a situation where you may use protected.

abstract class Preference
{
    protected abstract void Load();
    protected abstract void Save();

    public Preference()
    {
        Load();
    }

    ~Preference()
    {
        Save();
    }
}

class IntPreference : Preference
{
    protected override void Load()
    {
        //load from registry or config file
    }

    protected override void Save()
    {
        //save to registry or config file
    }

    public int Value { get; set; }
}

class StringPreference : Preference
{
    ...
}

class FloatPreference : Preference
{
    ...
}

By making the Load and Save methods protected we can make sure they are not called from outside the Preference class or one of its descendants. But we can call Load and Save from the base class and yet have the actual implementations supplied by derived classes that know how to handle the persistence.

I hope you have covered virtual methods already!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜