Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top