Java Reference
In-Depth Information
public class test{
public static void main(String args[]) {
Encapsulation encap = new Encapsulation ();
encap.setName("Rebecca");
encap.setAge(20);
system.out.println ("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}
}
As you can see in the above code, we are setting values of the variables in set methods and
values of the variables become available in the get methods which we can show on the user
screen.
You will also notice that we have introduced a new method of type “main”. Main methods
are used in one class to run code of that class as well as code of classes called inside that
class.
Public variables are the most dangerous things in programming. Most software defects oc-
cur because of these public variables. Avoiding public variables is one of the best weapons
to secure your code from defects. Using get and set methods (also known as Accessor and
setter methods) instead of public variables is one of the best practices in programming.
Search WWH ::




Custom Search