Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java allow accessing of a static member with an object instance

Tags:

java

oop

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?

like image 596
Myd Avatar asked Jun 16 '12 09:06

Myd


1 Answers

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.

like image 104
buc Avatar answered Oct 17 '22 06:10

buc