Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
like image 434
Simsons Avatar asked Dec 12 '22 09:12

Simsons


1 Answers

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.

like image 112
dougajmcdonald Avatar answered May 18 '23 16:05

dougajmcdonald