Domanda

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 ?

È stato utile?

Soluzione

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;
    }
}

Altri suggerimenti

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.

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.

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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top