Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

conflict: inheritance, package and import access

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Line 1 doesnt compile, I dont understand. Aren't protected members can be accessed through inheritance?

if package and import statements are omitted, it will compile fine and run fine.

All package and statement lines are properly declared. This is really confusing me.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Protected methods are inherited by subclasses, so the subclass can invoke its own inherited test() method. However, this still doesn't give it the right to invoke its parent's test() method using a parent reference.

In other words, if ClassA has a protected method myMethod, a class in a different package can never invoke myMethod() using a ClassA reference. This is true even if the other class is a subclass of ClassA. Being a subclass only gives it the right to invoke myMethod() using a reference to its own class type--not the parent's type.

It works when you remove the package declarations because this then puts both classes in the same package--and protected methods are always visible to all classes in the same package.
[ October 29, 2007: Message edited by: Kelvin Lim ]
 
Markus Schmider
Ranch Hand
Posts: 130
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the first problem is, that the class Parent is not declared public. It is not visible in other packages and therefore can not be inherited from in other packages.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Marcus Didius Falco:
I think the first problem is, that the class Parent is not declared public. It is not visible in other packages and therefore can not be inherited from in other packages.


Good catch! I was blind-sided by the fact that Adam specifically said that "Line 1 doesn't compile". So, um, yeah, fix the class visibility first, and then read my earlier comment.
 
srk bhushan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi adam,
In the above code you are trying to create an object of the superclass and access the members of the superclass but it is not possible, we can refer the super class members only through inheritance but not through the superclass's object from subclass.

Hope the above idea helps in clearing your doubt!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic