Here is an example:
int[] a = {10};
int x = a.length;
We read incessantly to hide variables and use accessors. Why was that rule violated here?
Here is an example:
int[] a = {10};
int x = a.length;
We read incessantly to hide variables and use accessors. Why was that rule violated here?
A bigger question is; why is there no class file for int[]
? Without such a class file there is no where to put such a method, so it is purely a language feature. It looks like a field of int[]
but it not. They could have made it look like a method call, but they didn't as it is an immutable field.
If you run this
public static void main(String[] args) throws NoSuchFieldException {
Field length = args.getClass().getDeclaredField("length");
it throws a NoSuchFieldException
as it is not a field like those in a class
but rather it is made to look like one.
We read incessantly to hide variables and use accessors.
It is not always necessary and in this case, there would be not benefit, only improve consistency.
According to Java documentation, length of an array is a final field. This means that no one can modify it, so there is no point in providing a setter for it.
Now since no one can modify it, there is no point for making that field private and providing a getter for it. A getter function will again be loaded into function stack in RAM memory, each time it will be called to get the size of an array. So, to increase performance, it makes sense to just make 'length' of an array as a public field.
On the other hand, a 'size()' method is provided in Collections class. This makes sense, because internal methods can allocate more memory and change the size of Collections.
We do not incessantly hide variables and use accessors. If it makes sense to provide a getter/setter, only then we should make a field as private and provide getter/setter for that.
One of the possible setback of using accessor is that if one day the return type of the accessor needs to be changed. All codes using the accessor method will encounter problems.
class MyClass{
private int val;
public int getVal(){
return val;
}
}
Imagine one day the return type of getVal() needs to be changed (e.g. to long
). This is one possible problem for all programs which uses getVal() because all along they have been expecting it to be of type int
.