• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in protected modifier

 
ramya ray
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21190
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Vaibhav Chauhan
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
child c = new child();
c.p1();

please check which type c is.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic