At the end of 2022, I started a quest to learn computer science. I want to become a programmer instead of a mere coder, and eventually a computer scientist instead of a mere programmer. I want to become so good they can’t ignore me. It’s an entire career’s worth of learning, but I feel excited rather than discouraged. Because I’m already proficient in JavaScript, a dynamically typed language, the first step of my journey is to learn a statically typed language. I chose Java, so I’m reading Core Java by Cay S. Horstmann.
In section 4.3.9 Class-Based Access Privileges, Horstmann writes:
“You know that a method can access the private data of the object on which it is invoked. What people often find surprising is that a method can access the private data of all objects of its class.”
This surprised me indeed! I think this is something I instinctively knew but never fully considered; it makes sense but it still caught me off guard. Horstmann offers the example of an Employee
class similar to the following:
class Employee
{
private String name;
public Employee(String n)
{
name = n;
}
public boolean equals(Employee other)
{
return name.equals(other.name);
}
}
Given the usage if (harry.equals(boss))
, Horstmann explains:
“This method accesses the private fields of
harry
, which is not surprising. It also accesses the private fields ofboss
. This is legal becauseboss
is an object of typeEmployee
, and a method of theEmployee
class is permitted to access the private fields of any object of typeEmployee
.”
This applies to JavaScript too!
class Employee {
#name;
constructor(name) {
this.#name = name;
}
equals(other) {
return this.#name == other.#name;
}
}