Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance and protected methods

 
Gunther Persoons
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using as IDE eclipse with java 1.5.0 update 6

I was trying this crazy idea of mine but I am not sure why this is working. I have following code :


It gives as output 'this is C' which I dont think is right cause C has the method test as protected so normally it can't be called outside it's package unless inherited. I thought it would give a runtime exception but apparently it doesn't. How is this possible? (Although this maybe never used in practice I thought it was a good exercise for the certification exam)
 
Harshil Mehta
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Certainly it's a good exercise for exam, while first time going through code, i also thought same as you. :roll:

But look at the class of object to which reference testA is referring. Eventhough class of reference testA is A, but the object to which it's referring is of class C. So at the runtime, it's actually object of class C only, which is trying to access a method of same class(i.e. class C).

So the output should be 'this is C' only.
--Harshil
 
Gunther Persoons
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I understand it. So at runtime it doesn't matter that the method is protected and the class is in another package because at because compile time it sees the class as an A class and this isn't checked anymore at runtime.
 
Tor Henning Post
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe a bit late, but "protected" is actually less strict than the default "package" accsess modifier.

protected methods will always be visible in sub classes and to classes in the same package.

the default accsess modifier is ONLY visible in the same package, so if you extends the class in another package the protected methods of the super class will not be visible
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tor Henning Post:
Maybe a bit late, but "protected" is actually less strict than the default "package" accsess modifier.


Mhh, I didn't see something in this thread that conflicts with this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic