aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in protected modifier Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in protected modifier" Watch "Doubt in protected modifier" New topic
Author

Doubt in protected modifier

ramya ray
Ranch Hand

Joined: Aug 11, 2006
Posts: 101
It is mentioned that a subclass outside the package can not access member which has protected modifier using a reference to an instance of superclass..

But below code gives the different behaviour.

package fruit;
public class parent{

protected static void p1( ){
System.out.println("Parent class");
}
}

import fruit.parent;
public class child extends parent{
public static void main (String ARGS[]){
child c = new child();
c.p1();
}
}

class child complies and output : "parent class"

Please explain why it is not giving the compile error.

Thanks in advance.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Here you are not accessing the method p1() with a superclass reference. You are accessing it with a subclass reference.
[ September 11, 2006: Message edited by: Keith Lynn ]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18101
    
  39

protected methods may be accessed from any class in the same package and any subclass. Since child is a subclass, it may call the protected method, even though it is not in the same package.




[Clarification: By "and", I did not mean to imply that subclass must be in the same package. I meant that any class in the same package *and* any subclass regardless of package location, may access the protected method.]

Henry
[ September 11, 2006: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Vaibhav Chauhan
Ranch Hand

Joined: Aug 16, 2006
Posts: 115
if you want to challenge the quote that you mentioned, write:



this will not compile.

hope you got it.
[ September 12, 2006: Message edited by: Vaibhav Chauhan ]
Chetan Raju
Ranch Hand

Joined: Aug 02, 2006
Posts: 109
child c = new child();
c.p1();

please check which type c is.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in protected modifier
 
Similar Threads
Protected - access modifier
Child extends Parent, Belongs to same package, Cannot access public variable
query on method over riding
Protected Access Modifier
question regarding package and import..