I am aware that if you subclass a class (superclass) which has for example an instance variable, it is going to be inherited in the subclass.
i.e. :
class Weather {
int humidity;
}
public class Rainy extends Weather {
void changeHumidity() {
humidity = 10;
System.out.println(super.humidity);
}
public static void main(String[] args) {
new Rainy().changeHumidity();
}
}
Bottom line: I would like to know why the instance variable “humidity” gets shared between subclass and class.
I am aware that if I shadowed that, it would not be shared but still why another instance (even though is the superclass) should share a variable with the subclass in the inheritance logic.
Thanks in advance.
There were two decisions the creators of Java took that guided how they designed Java. One was that performance was a priority, it must not be judged unusable due to being too slow. The other decision was that they would target C and C++ developers, and make Java similar to what they were used to in order to make adoption easier.
So Java got public, private, and protected access like C++. Where package-private came in and why it is the default is not clear. They might have assumed developers would want to access variables directly in order to save on method call overhead. A long time ago I was working on a project with professional services people from Marimba, and we had the opportunity to investigate some of the implementation code, which was written with a lot of package-private members. When I asked why the explanation was it was for performance. This was before optimizations like JIT, so there may have been a concern that using accessor methods to get to frequently used superclass members might be too slow. On the other hand it might have been a style preference or they were using a freer approach as part of an evolving design, and maybe the idea behind making package-private the default was that this kind of freedom should be expected. (It’s not something that has caught on judging by any other code I’ve read.) It was code written by Jonathon Payne and Arthur Van Hoff, so the professional service people may not have been in on the real reasons.
There’s an interview where James Gosling talks about his reasons:
The direction in which the style has evolved has been to prefer making instance variables private, and expose them through getters if required. You can specify the private access modifier, like this:
and then the variable won’t be visible to the subclass.