Rule of thumb for a new programmer:
Data is private within a class, methods are public.
If we have the class Thing, for instance:
- public class Thing{
-
// private data
-
private String name;
-
private int age;
-
-
// public accessor methods
-
public String getName(){
-
return name;
-
}
-
-
public int getAge(){
-
return age;
-
}
-
-
// public mutator methods
-
-
public void setName(String n){
-
name = n;
-
}
-
-
public void setAge(int a){
-
age = a;
-
}
-
-
}
In most of your typical introductory work in Java, creating classes in this way will allow you to make your classes public 99% time. As stated above, however, more advanced programming (requiring inheritance and interface classes) will cause you to start recognizing more effective ways of declaring things public or private...
Creating these kinds of accessor (get data) methods and mutator (change data) methods is usually considered good practice...
Until again,
Tom