And I don't really understand what's going on - my application still works the same as before.
It does, but differently. First you had a public int BagsOfFeed
in the class that could be accessed and changed from anywhere in your program.
This would work:
farmer.BagsOfFeed= 1;
int i = farmer.BagsOfFeed; // i is now 1
farmer.BagsOfFeed= 5;
i = farmer.BagsOfFeed; // i is now 5
General guideline however is to not use public fields because they can be changed from anywhere in your program. There are situations (I know the book explains at least 1 example, about calculating party costs if I recall correctly) where that could mess up the output of your program.
To prevent that from happening we use properties to encapsulate the fields.
That hasn’t fixed our problem yet. But there’s an easy fix—just make it a read-only property: Try to rebuild your code—you’ll get an error on the line in the button that sets
BagsOfFeedtelling
you that the set accessor is inaccessible. You can’t modifyBagsOfFeedfrom
outside theFarmerclass
.
What you are meant to do is make your property read only:
public int BagsOfFeed
{
get;
private set;
}
Note the private
before the set
. What this does is make the property so it can be get from anywhere but can only be set from inside that class. BagsOfFeed is now encapsulated.
In this particular example the property omits the need for implementing methods like farmer.getBagsOfFeed()
and farmer.setBagsOfFeed(n)