Protection Test
Question: If one has a handle to an instance, do they really have
the instance? Specifically, given a Class A which has an instance variable
of type Class B, can Class A access the private components of Class B since
Class A has possession of the thing called Class B (specifically, Class A
has Class B's identity (handle))
The following is a test for how protections work.
First, a class that has protected variables:
public class CheckProtect {
private int amPrivate=1 ;
int amNot=1 ;
public void changeBoth() {
amPrivate++ ;
amNot++ ;
}
private void changePrivate() {
amPrivate++ ;
}
public void changePublic() {
amNot++ ;
}
}
Now a class to test it. Notice the main() method:
public class TestProtect {
CheckProtect testMe ;
public TestProtect() {
testMe = new CheckProtect() ;
}
public static void main(String args[]) {
TestProtect makeOne = new TestProtect() ;
makeOne.testCheck();
}
public void testCheck(){
testMe.amNot++;
printTest();
testMe.changePublic();
printTest();
testMe.amPrivate++;
testMe.changePrivate();
printTest();
testMe.changeBoth();
printTest();
}
public void printTest(){
System.out.println("This" + testMe.amPrivate + " is amPrivate and this "
+ testMe.amNot + "is not"); }
}
CheckProtect compiles fine. When compiling TestProtect we get
TestProtect.java:23: Variable amPrivate in class
CheckProtect not accessible from class TestProtect.
testMe.amPrivate++;
^
TestProtect.java:25: No method matching changePrivate()
found in class CheckProtect.
testMe.changePrivate();
^
TestProtect.java:32: Variable amPrivate in class
CheckProtect not accessible from class TestProtect.
System.out.println("This" + testMe.amPrivate + " is amPrivate and this " + testMe.amNot + is not");
^
3 errors
So, let's change some things. Remove
testMe.amPrivate++;
testMe.changePrivate();
and change the printTest() to:
public void printTest(){
System.out.println("This: " + testMe.amNot + " is amNot"); }
Then, put a printTest() in CheckProtect as well:
public void printTest(){
System.out.println("Test from CheckProtect: this " + this.amPrivate
+ " is amPrivate and this " + amNot + " is amNot"); }
Recompiling (works fine) and running produces:
This: 2 is amNot
This: 3 is amNot
Test from CheckProtect: this 2 is amPrivate and this 4 is amNot
This: 4 is amNot
Lesson: having a handle to an instance and calling methods with it
is not the same as calling methods from "within the class". Private
methods and instance variables can only be reached via
Public methods of that same class.
Then, next question: Can any class ever have all private components?