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.

4 comments:

Anonymous said...

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

nekrataal said...

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

SBCGlobal Support said...

Despite of enhanced Yahoo features, tech issues are also introduced at a vast level of difficulties. SBCGlobal Customer Service provides help for the problems faced during the usage of a new interface. We have a team of experts which assists you on how to download files, install and backup your important emails with all the new features. If you are dealing with any issue related to SBCGlobal account, please contact us at SBCGlobal Support Phone Number where you get support via highly experienced and efficient technicians. Just talk to our technical support executives who will entertain you while fixing your glitches.

James Zuniga said...

I enjoyed reaading your post