When you instantiate an object of child class.
- All fields of parent as well as child class are initialized, irrespective of access modifier (private, protected or public)
- Constructor of parent class is called.
- Constructor of child class is called.
So the fields will exist (and they will store a value), but you won't be able to access them if they are private.
The public method returning a private field will grant you that access. In a nutshell, it will work.
Hope this helps.
Edit (in response to the comment):
The mechanism is built right into the language for security. Access modifiers provide information required to that mechanism.
- A private field can only be accessed from within the class.
- It will be present but not visible from outside.
- You can sense it's presence by the effect it has on the behavior of some of the public methods of that class (ones which use it). Since those methods are members of the same class, they can access the private field.
Benefits:
- You can hide implementation details from outside.
- You can restrict the improper usage of the fields through method.
Example
private int salary;
public void setSalary(int newSalary) {
if (newSalary < MAX_SALARY) {
this.salary = newSalary;
} else {
this.salary = MAX_SALARY;
}
}