Instance variable is a variable declared within the class for which every object of the class has its own value.
In Java, making a class field public
can cause lot of issues in a program. For instance you may have a class called MyCompany. This class contains an array of String companies.
You may have assume that this array will always contain 4 names of companies. But as this array is public, it may be accessed by anyone. Someone by mistake also may change the value and insert a bug!
public class MyCompany { public String[] companies = {"Google", "Yahoo", "Microsoft", "Paypal"}; //some code }
Best approach as many of you already know is to always make the field private
and add a getter
method to access the elements.
private String[] companies = {"Google", "Yahoo", "Microsoft", "Paypal"}; public String[] getCompanies() { return companies; // imperfect code }
But writing getter method does not exactly solve our problem. The array is still accessible. Best way to make it unmodifiable
is to return a clone of array
instead of array itself. Thus the getter method will be changed to.
public String[] getCompanies() { return companies.clone(); // better code }