Reputation: 21901
class Parent{
private int a = 10;
public int getA() {
return a;
}
}
class Child extends Parent{
public int b = 20;
public void getSuperA() {
System.out.print(getA()); // getA() instead of a
}
}
when we creating a child class object only one object will create. what are the members in that object ? what will happen to the private field in the Parent ?
Upvotes: 3
Views: 2402
Reputation: 7057
When you instantiate an object of child class.
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.
Benefits:
Example
private int salary;
public void setSalary(int newSalary) {
if (newSalary < MAX_SALARY) {
this.salary = newSalary;
} else {
this.salary = MAX_SALARY;
}
}
Upvotes: 2
Reputation: 2354
it seems you know if you do something
Child ch = new Child()
and then
ch.a;
obviously not working, because it's private but when an object extends from a parent class it inherits all the public and private attribute so you have to define a function in Parent class like
public int getA(){
return a;
}
and later on in ch you can access a like this :
ch.getA();
Upvotes: 0
Reputation: 122364
The child object will hold a value for the parent's private field, but because it's private in Parent
the only way for anyone (including the child object itself) to access the value is via the methods inherited from the parent class.
Upvotes: 1
Reputation: 842
Chile object's fields are created. First fields are initialised, then constructor is invoked. In your case field a will be initialised with value 10.
Upvotes: 0