-3

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?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • 4
    Have you tried? That would have probably taken less than writing the questions here. – Edwin Dalorzo Apr 15 '14 at 15:33
  • http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private?rq=1 – xd6_ Apr 15 '14 at 15:33
  • http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – coreJavare Apr 15 '14 at 15:34
  • `private modifier`—the field is accessible only within its own class. – Nambi Apr 15 '14 at 15:34
  • Do not understand pseudo-code or any human language, only understand code. Please show code. – CodeCamper Apr 15 '14 at 15:34
  • You know, in the time this question will be downvoted and closed, you could have found out for yourself by *writing some code* rather than asking people to tell you the answer. – Brian Roach Apr 15 '14 at 15:35
  • @NambiNarayanan Is there a way to allow a field/method to be inherited by subclasses, but not accessible by any other class? I.e., only accessible by the subclasses? – Aviv Cohn Apr 15 '14 at 15:41
  • @Prog Use the `protected` modifier for that. – Nambi Apr 15 '14 at 15:44
  • @NambiNarayanan But that allows all classes in the package access, which pretty much brakes encapsulation. If this is the only option, it's a problem with Java isn't it? – Aviv Cohn Apr 15 '14 at 15:45
  • @Prog I think the idea is that a package is something you create to bundle up closely related types that cooperate with each other. Another programmer using your package might extend (subclass) one of your types, but he wouldn't define a new type in your package. So in this scenario, it would be considered OK for members to be accessible to other classes, but only the closely related ones. See also [this tutorial](http://docs.oracle.com/javase/tutorial/java/package/packages.html). – ajb Apr 15 '14 at 16:03

2 Answers2

0

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

DreadPirateShawn
  • 8,164
  • 4
  • 49
  • 71
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
0

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;
}
davioooh
  • 23,742
  • 39
  • 159
  • 250