|
Hi guys I need some one who really worked in series project to explain some concept
my teacher making a big story about private variable.
people always says we used private to make java hide the containing
.
package Student;
public class Student {
public static void main(String[] args) {
information x = new information();
x.ID();
{
package Student ;
public class information{
private int ID=0;
private string name="";
private int GPA =0;
}
I know I can't change ID without using set and get but this my question
if I will use set and get I can make my life easy just make ID like this
public int ID=0;
instead using set and get method.
my teacher said to protect the information from user !!!!!!!!
I don't why he said that ?
because user will see message like enter number and then the code will do calculation
like :
Please enter two Numbers :
5
4
The result : 9
So I still I don't know why I should use private which force me to use set and get .
please guys help me and remember I know this stupid question but I ask because I know how to use private but I don't why ?
before I just write this question I read and watch online youtube but there nothing I get
I'm a person who has only small memory takes only logical things and throw illogical thing.
|
|
|
|
|
See this description[^].
One of these days I'm going to think of a really clever signature.
|
|
|
|
|
You have to protect variables, because you depend in them.
Limiting the access to the getter and setter, you can depend on the variables to be used in the context you expect to have them.
Also, you can validate the value on the setter, which gives you the chance to to reject the value in case it is not ok (throw Exception). This protects your code from failing.
As a 3. argument: The same variable can be part of different methods/classes. but each name of a variable has to be unique, otherwise the code will fail.
So one limits down the range, where the variable exists as much as possible. therefor, one can use the same name again - not that one does it constantly, but one has the chance to.
And last but not least: it's simply good design/style to do so.
The usage of static should also be limited as much as possible.
There are some occasions where it is needed - but that should be used as less as possible.
Please read about the "encapsulation" - the link, that Richard posted. And please do some more research.
This is a basic of java development. One can't go without this, so you need to understand it.
|
|
|
|
|
guys I really grateful for your answers
|
|
|
|