Friday, December 10, 2010

Why property is a better choice instead of public variables?

Property Vs. Public Variable
Properties are better than public variables There are two reasons.

1) Public variables are unsafe, as anyone can set any value and you have no control over them.While in case of property you can put a check that no one could set invalid value to them.

Suppose you have a property Salary..

private int m_iSalary=100;

property int Salary
{
get
{
return m_iSalary;
}

set
{
if(value > 0)
{
m_iSalary=value;
}
else
{
MessageBox.Show("You can not set Negative value in Salary.");
}
}
}

2) We can restrict any one, that he can only get the value but could not set from outside of class and vise versa.

property int Salary
{
get
{
return m_iSalary;
}

private set
{
if(value > 0)
{
m_iSalary=value;
}
else
{
MessageBox.Show("You can not set negative value in Salary.");
}
}
}

But inner access modifier should be more restrictive than main access modifier. We can not define access specifier for both(get and set) in one property, You can set only one at a time. And other will use main access specifier.

In set method value is a keyword you can not use any hard code value or any other variable instead of value keyword.

2 comments:

fabioborini21 said...

Hi

I read this post two times.

I like it so much, please try to keep posting.

Let me introduce other material that may be good for our community.

Source: Property interview questions

Best regards
Henry

JP@classpath in java said...

Nice article , questions are good and answers are crisp. I have also blogged my experience as Top 20 Core Java Interview questions and answers . let me know how do you find it.

Followers

Link