Response: Private/Instance Variables

ChiliJoe posted in Access to Instance Variables within the Same Class that an instance can change the value of another instance’s private variable.

At first, this sounds like it doesn’t make sense — an instance shouldn’t be able to access something private to another instance. But, in my opinion, the private is to protect it from code that may not understand or may violate rules the class depends on. From that point of view, it does make sense. Whoever wrote the code for the class knows what the value should be, and therefore, can be trusted to change it. Therefore, it can change any instance’s private variable as long as it is the same class. Whoever wrote the other class may not even be able to look at the code to see if they are going to mess things up, and therefore, cannot access the variable.

I think the PeopleSoft names make it confusing. Instead of calling it private, PeopleCode calls it instance, which would lead you to think that only that instance could access it. Actually, it is private to the class, not the instance.

So, to take the challenge, I translated ChiliJoe’s code to Java just to see if it works the same in Java. It does:

package com.skp.peoplecodejavacompare;

public class Example {
private Example newInstance;
private int num = 0;

public void createNewInstance() {
newInstance = new Example();
}

public int incrementNewInstanceNum() {
newInstance.num++;
return newInstance.num;
}

public int incrementThisInstanceNum() {
num++;
return num;
}

public void incrementPassedNum(Example passed) {
passed.num ++;
}

public int getThisInstanceNum() {
return num;
}

public static void main(String[] args) {
Example test1 = new Example();
test1.createNewInstance();

System.out.println(“incrementNewInstanceNum returns “ + test1.incrementNewInstanceNum());
System.out.println(“getThisInstanceNum returns “ + test1.getThisInstanceNum());
System.out.println(“incrementThisInstanceNum returns “ + test1.incrementThisInstanceNum());
System.out.println(“incrementNewInstanceNum returns “ + test1.incrementNewInstanceNum());

Example test2 = new Example();
System.out.println(“test2.getThisInstanceNum returns “ + test2.getThisInstanceNum());
test1.incrementPassedNum(test2);
System.out.println(“test2.getThisInstanceNum returns “ + test2.getThisInstanceNum());
}
}

Output:

incrementNewInstanceNum returns 1
getThisInstanceNum returns 0
incrementThisInstanceNum returns 1
incrementNewInstanceNum returns 2
test2.getThisInstanceNum returns 0
test2.getThisInstanceNum returns 1

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.