Sunday, March 4, 2007

Access modifier : "private" for distinct instances of the same class

Many of us who are reading this blog might have learned the use of access modifiers in Java. I found that there is a small confusion about the use of "private" access modifier.

private
member
Accessible only in its class(which defins it).
protected
member
Accessible only within its package and its subclasses
public
class

interface

member

Accessible anywhere

Accessible anywhere

Accessible anywhere its class is.

Let us create a new class named "Student".

public class Student {
private int score;

public Student() {
score = 89;
}

public void modifyScore(Student that,int newValue){
that.score = newValue;
}

public String toString() {
return "Score = " + score;
}

}


Imagine a situation where instance "A" of class "Student" trying to modify the "score" member of instance "B" of the same class, The misunderstanding is this cannot be done because of the score's access modifier is private. In fact, it can be done correctly. As the rule states that private members are accessible only in its class. So instances could access the private members of other instances too.

2 comments:

deans4j said...

-*- เค้าสับสนกันเรื่องนี้กันด้วยหรอเนี้ยะ

Nekrataal said...

เดี๋ยวจามี static กับ friend ตามมาด้วยป่ะ อุอุอุ