Domanda

In Java, class A defines a member variable private int num; Class B is a subclass of class A.

1- If the two classes are in the same package - does B inherit num?

2- If the two classes are not in the same package - does B inherit num?

È stato utile?

Soluzione

B does not inherit or have access to num in either of those cases.

Altri suggerimenti

In any case a subclass can access to a method or variable if this is declared as private in a superclass.

The only way to allow access to your num field is providing public (or at least protected) accessors method:

public int getNum(){
    return this.num;
}

public void setNum(int num){
    return this.num = num;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top