• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Modifier protected does not hide inherited members to (static) code of superclass package Query

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have changed the code a bit.

AClass.java


BClass.java


Test.java


OUTPUT:
A
B
Super:
A
A

K&Bs Book tells me on Page 36:
Once a Subclass-outside-the-package inherits the protected member, that member (as inherited by the subclass) becomes private to any code outside the subclass, with the exception of subclass of the subclass.


here,m is protected member of AClass that is inherited by BClass.so,by above statement m in BClass would be Invisible outside BClass.
but ,it is accessible in Test.java

SEE LINE 8,11

how is this possible ?
 
Aneesh Vijendran
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class BClass extends AClass {
private int m=12;
[public [/b]void m1()


You have made it public. How could it be private?

Cheers
Aneesh
 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i am talking about m method and not m1
 
Aneesh Vijendran
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mohit,

Your Test.java & AClass.java are using the same package (package A)

If you expect this not to work, then you should override the m method in BClass.java

Hope this clears.

Cheers
Aneesh
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Make m() method as private in the class AClass, and see what happens!
 
Alexander Exner
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
AFAIK this happens:
1) Compiler indeed does not see inherited protected method m() in package B (BClass).
2) Therefore compiler looks at superclasses and finds protected method m() as defined in package A (AClass). Compiler is happy with that because its the same package as the "caller".
3) Runtime behavior was in my original example (http://www.coderanch.com/t/504882/java-programmer-SCJP/certification/Modifier-protected-does-not-hide) different, but in this example the JVM has only one choice as well: m() from AClass.

Maybe K&B should go a little bit more in detail on page 36...

KR Alex
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic