My understanding is that static members belong to the class. Why then does Java allow me to access them with an object?
To understand what I mean, please see the following example:
public class Student {
public static int number = 0;
}
Here number
is a static field that belongs to class Student
, but I can still access it as shown below:
Student s = new Student();
int n = s.number;
What is the rationale behind this decision?
The rationale behind this is that an object is an instance of the class, and therefore it should be able to access every attribute that belongs to the class in addition to the the instance level attributes.
It's like traditional mail. If you receive a mail that were addressed to your whole family (static member), you will feel licenced to open it, because you are the member of the family. On the other hand, if the mail is addressed to you (instance member), only you have the right to open it, no one else in you family.
This also works the same in other object-oriented languages, like C++. However, it is discouraged to use the s.number
notation to access static members, as it is misleading for the readers of your code. You should always use the Student.number
notation, as this clearly shows that number
is a static member. Modern languages, for example C# will issue a warning if you access static members via instance variable, but still it is perfectly legal according to the language specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With