File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Inheritance and protected methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Inheritance and protected methods" Watch "Inheritance and protected methods" New topic

Inheritance and protected methods

Gunther Persoons

Joined: Apr 13, 2006
Posts: 2
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

Joined: Mar 17, 2005
Posts: 64
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.
Gunther Persoons

Joined: Apr 13, 2006
Posts: 2
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

Joined: Nov 14, 2003
Posts: 11
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

Joined: Jul 11, 2001
Posts: 14112
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.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: Inheritance and protected methods
It's not a secret anymore!