Ok. You have to consider something called: scope.
There are 4 keywords which indicate:
Access Level (read:
Controlling Access to Members of a Class (The Java™ Tutorials > Learning the Java Language > Classes and Objects))
For our purposes, we are going to leave one out, and just say there are 3:
1. public
2. protected
3. private
These keywords go in front of instance variables, constructors, and methods to determine who can access the variables, constructors, or methods. To keep it simple, here are the basic rules:
Public indicates it can be referenced by anyone.
Protected indicates that it can only be referenced within its own class and by any subclasses.
Private indicates that it can only be referenced within its own class (no subclasses even).
So, let's say we have two classes:
public class A {
private int var1;
protected int var2;
public int var3;
}
public class B extends A {
}
Now let's say we have a third class. This class will create a new instance of A and attempt to reference the variables. Read the comments to see how that works out:
public class C {
public C() {
A obj = new A();
obj.var1; // NOT ALLOWED - var1 is private
obj.var2; // NOT ALLOWED - var2 is protected
obj.var3; // ALLOWED - var3 is public
}
}
Now let's expand the B class, doing the same sort of thing:
public class B extends A {
public B() {
this.var1; // NOT ALLOWED - var1 is private
this.var2; // ALLOWED - var2 is protected, and B inherits from A
this.var3; // ALLOWED - var3 is public
}
}
Lastly, let's expand A to do the same thing:
public class A {
private int var1;
protected int var2;
public int var3;
public A() {
this.var1; // ALLOWED - var1 is private, but we are in the A class
this.var2; // ALLOWED - var2 is protected, but we are in the A class
this.var3; // ALLOWED - var3 is public
}
}
Now, let's say class C really needed access to var1 or var2. How can we give it access without changing the access level of either variable? By creating getters:
public class A {
private int var1;
protected int var2;
public int var3;
public int getVar1() {
return var1;
}
public int getVar2() {
return var2;
}
}
public class C {
public C() {
A obj = new A();
obj.var1; // NOT ALLOWED - var1 is private
obj.var2; // NOT ALLOWED - var2 is protected
obj.var3; // ALLOWED - var3 is public
obj.getVar1(); // ALLOWED - var1 is private, but getVar1() is public
obj.getVar2(); // ALLOWED - var2 is protected, but getVar2() is public
}
}
Do you understand all of that?