• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Protected Visibility - what am I missing?

 
Jaspreet Singh
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why is CODE] sub.protectedmethod()[ [/CODE]giving a visibiliy error.

Why should it matter to visibility where from (Test) I am invoking the object's method, all that should matter is what is available to the object that I am invoking the method on. And of course, the protectedmethod() is available to MySubClass via inheritence from MyObject.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jaspreet Singh:
[CODE]
Why should it matter to visibility where from (Test) I am invoking the object's method, all that should matter is what is available to the object that I am invoking the method on. And of course, the protectedmethod() is available to MySubClass via inheritence from MyObject.


True, protectedmethod() is available to MySubClass, but it is NOT available to Test because it's protected. The visibility modifiers (public, protected, and private) affect what other classes are allowed to call a method. Since protectedmethod() is protected, it can only be called by subclasses (and technically by other non-subclasses in the same package as well). Since Test is not a subclass and in a different package, it cannot call protectedmethod(). In order to allow Test to call the method, you need to redeclare it as public in MySubclass.

Layne
 
Jaspreet Singh
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The visibility modifiers (public, protected, and private) affect what other classes are allowed to call a method.


Well, if thats true, then making Test a subclass of MyObject should allow sub.protectedmethod(), isnt it? It still gives an error.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic