Protected JavaRanch 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 46

A friendly

place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this week in the Web
Services forum!

JavaRanch Java Forums Java Beginning Java


Author
Protected Access Modifier
rizwana
mujawar
Ranch Hand

Joined: Feb 24,
2012
Posts: 36
posted Wednesday, March 28, 2012 14:55:28


Friends Iam studying SCJP book...
Now this protected modifier section is killing and confusing me... Ok let me start...
I have a class Parent in one package,the Child class in another package inherits the protected
member... upto here its working fine...
Now SCJP books reads that.... "what if another class in same package as a Child class can access
the protected member of Parent through Child by instantiating the Child class...?
The answer given in the book was straight forward i.e,no.. They further told that the protected
member accessed by subclass will behave private to all other class from here onwards....
For example:A class Neighbour in the same package as that of Child",can access the protected
member of Parent through Child "...
SCJP book is atleast saying no but when i try to do it practically the answer is quiet different... Any
suggestion where y understanding is going wrong...?.
I have written down the code here which is working fine but voilating what My SCJP book is
telling...
view plaincopy to clipboardprint?
1. package let;
2. public class Parent
3. {
4. protected void hmmm()
5. {
6. System.out.println("Iam protected");
7. }
8. }
9.
10. package kya;
11. import let.Parent;
12. class Child extends Parent
13. {
14. public void test()
15. {
16. System.out.println("Are you protected:");
17. this.hmmm();
18. }
19. }
20.
21.
22. package kya;
23. class Neighbour
24. {
25. public void letMeTry()
26. {
27. System.out.println("Can i acsess the protected member through my friend Child...?");
28. Child c=new Child();
29. c.test();
30. }
31.
32.
33. public static void main(String args[])
34. {
35. Neighbour n=new Neighbour();
36. n.letMeTry();
37. }
38. }

Mohamed
Sanaulla
Bartender

Joined: Sep 08,
2007
Posts: 2837

I like...

posted Wednesday, March 28, 2012 15:19:35


Did you try c.hmmm();? It says that accessing the protected method other than through
inheritance in a different package is not possible. But in the example you are accessing the
protected method in the instance of Child class, so you are still in the context of the Child class.


Mohamed Sanaulla | My Blog



okay, here's the link: http://aspose.com/file-tools


subject: Protected Access Modifier




Similar Threads
protected member access

protected modifier

K&B Ch10#8 protected access question

Doubt in protected modifier

Protected Modifier

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:49:20.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton


more from paul wheaton's glorious empire of web junk: cast iron
skilletdiatomaceous earth rocket mass heatersepp holzer raised garden
beds raising chickens lawn care light bulbs flea controlmissoula electric
heaters permaculture



A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this
week in the Web Services forum!

JavaRanch Java Forums Professional Certification Programmer
Certification (SCJP/OCPJP)


Author
Doubt in protected modifier
ramya ray
Ranch Hand

Joined: Aug 11,
2006
Posts: 101
posted Tuesday, September 12, 2006 02:25


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: 2306
posted Tuesday, September 12, 2006 02:35


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: 16049
I like...

posted Tuesday, September 12, 2006 03:05


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
posted Tuesday, September 12, 2006 09:53



if you want to challenge the quote that you mentioned, write:
view plaincopy to clipboardprint?
1. parent p=new child();
2. p.p1();


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
posted Tuesday, September 12, 2006 12:01



child c = new child();
c.p1();

please check which type c is.





I agree. Here's the link: http://ej-technologies/jprofiler


subject: Doubt in protected modifier




Similar Threads
question regarding package and import..

Child extends Parent, Belongs to same package, Cannot access public variable

query on method over riding

Protected Access Modifier

Protected - access modifier

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:55:12.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton

more from paul wheaton's glorious empire of web junk: cast iron
skillet diatomaceous earth rocket mass heater sepp holzerraised
garden beds raising chickens lawn care light bulbs flea
control missoulaelectric heaters permaculture



A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this week in the Web
Services forum!

JavaRanch Java Forums Professional Certification Programmer Certification
(SCJP/OCPJP)


Author
Child extends Parent, Belongs to same
package, Cannot access public variable
Sandra Bachan
Ranch Hand

Joined: Feb 18,
2010
Posts: 431
posted Wednesday, June 09, 2010 06:22:21


Hello,

I have two programs based on code from Sierra/Bates Chapter 1:

location: /one/src/Parent.java
view plaincopy to clipboardprint?
1. package certification;
2.
3. public class Parent {
4. public int x = 9;
5. }


location: /one/src/Child.java

view plaincopy to clipboardprint?
1. package certification;
2.
3. class Child extends Parent {
4.
5. public static void main (String[] args){
6.
7. System.out.println("x is " + x);
8. }
9. }


I navigate to one directory and type in javac -d ./classes/ ./src/Parent.java
./src/Child.java. Below is the error:

non-static variable x cannot be referenced from a static context
System.out.println("x is " + x);


One would think the code compiles and executes considering that Child inherits from Parent,
Child is in same package as Parent, and the variable is PUBLIC.




Christophe
Verr
Sheriff

Joined: Nov 24,
2005
Posts: 14563
I like...

posted Wednesday, June 09, 2010 06:33:50


The problem is that you are accessing the instance variable from the main method, which is a
static method. Read the error message again : non-static variable x cannot be referenced
from a static context. I don't know if you have already studies what static variables and static
methods are. Try to make a public non static method in Child, and try System.out.println("x is "
+ x); again.


[My Blog]
All roads lead to JavaRanch

Sahil Kapoor
Ranch Hand

Joined: Sep 12,
2009
Posts: 316
posted Wednesday, June 09, 2010 11:20:17



Hello sandra Bachan , this is the most frequent mistake encountered by JAVA learners.

Just to follow one rule :

Non-Static members cannot be accessed from Static context ie Static methods directly without
referring to any object.

Reasoning :- Static members could exist before object creation.

So when you are trying to access variable x which is inherited from the parent class, it is still
non- static. You try to access a non-static variable from the static main method and hence the
error. Because at that time if suppose,say, 100 objects of the child class already exists on the

heap, then compiler complains because it does not resolve that whose x are you trying to refer .

But But But if you say i am referring to object number ,say 75, then you would say ob75.x , now
compiler knows that you are referring to x which exists inside object75, and hence it is allowed.



SCJP 6.0 96%

(Connecting the Dots ....)

Martin
Vanyavchich
Ranch Hand

Joined: Sep 16,
2008
Posts: 241
posted Wednesday, June 09, 2010 11:55:50



All that said, you have two options to make that work

One way, make x static:
view plaincopy to clipboardprint?
1. package certification;
2.
3. public class Parent {
4. public static int x = 9; // note the static modifier
5. }

view plaincopy to clipboardprint?
1. package certification;
2.
3. class Child extends Parent {
4.
5. public static void main (String[] args){
6.
7. System.out.println("x is " + x);
8. }
9. }

Second way, instantiate Child or Parent and invoke the call on the object:
view plaincopy to clipboardprint?
1. package certification;
2.
3. public class Parent {
4. public int x = 9;

5. }

view plaincopy to clipboardprint?
1. package certification;
2.
3. class Child extends Parent {
4.
5. public static void main (String[] args){
6. Child child = new Child(); // would work with Parent class too
7.
8. System.out.println("childs x is " + child.x);
9. }
10. }



Hope this helps


SCJP 6, OCMJD 6, OCPJWSD 6
I no good English.

Sandra Bachan
Ranch Hand

Joined: Feb 18,
2010
Posts: 431
posted Saturday, June 12, 2010 18:56:06



These are all very helpful and now my code works.Thanks guys!

@ Sahil: I really appreciate you including the reasoning, i.e. static members can exist before
object creation





I agree. Here's the link: http://ej-technologies/jprofiler


subject: Child extends Parent, Belongs to same package, Cannot access public variable




Similar Threads
default vs protected access

Classpath Trouble

bet u cant ans this

Code from SCJP K&B Book won't compile

problem on extending a class declared on the same package!!

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:55:50.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton


more from paul wheaton's glorious empire of web junk: cast iron
skilletdiatomaceous earth rocket mass heatersepp holzer raised garden
beds raising chickens lawn care light bulbs flea controlmissoula electric
heaters permaculture

This week's book giveaway is in the Web Services forum.
We're giving away four copies of Restlet in Action and have
Jerome Louvel, Thierry Templier, and Thierry Boileau on-line!
See this thread for details.

A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this
week in the Web Services forum!

JavaRanch Java Forums Professional Certification Programmer
Certification (SCJP/OCPJP)


Author
default vs protected access
Gyan Shankar
Ranch Hand

Joined: Dec 12,
2005
Posts: 65
posted Saturday, December 24, 2005 10:34


Why is default more restrictive than protected? this is what is read in books.
default members can be accessed via the reference.member but for
protected you cant do this.

Please explain

Check this

Parent.java
view plaincopy to clipboardprint?
1. package cert;
2. public class Parent
3. {
4. int a = 10;
5. }


Child.java
view plaincopy to clipboardprint?
1. package cert;
2.
3. public class Child
4. {
5. public int useParent()
6. {
7. Parent p = new Parent();
8. return p.a;
9. }
10. }


Use.java
view plaincopy to clipboardprint?
1. import cert.*;
2. public class Use
3. {
4. public static void main(String[] args)
5. {
6. Child c = new Child();
7. System.out.println(c.useParent());
8. }
9. }


This code wont work if int a = 10 is made protected.

I think default can do certin things which protected cant
also protected can do certain things which default cant

So why is it said default is more restrictive?

[ December 23, 2005: Message edited by: Jeff Kumar ]
[ December 23, 2005: Message edited by: Jeff Kumar ]

SCJP(1.4), SCWCD(1.4), SCBCD(1.3), SCDJWS

vipul patel
Ranch Hand

Joined: Oct 16,
2005
Posts: 146
posted Saturday, December 24, 2005 12:43



when you are saying default, it means that it is package level accecibility. it
is NOT available outside of the package. try it.

in contrast to that, protected is visible outside package also. But there is
important difference here.

protected has something to do in subclasses. so a protected member in
superclass is also visible in subclass of that defined in another package.
where as default is not.

I think you can try out different situations with some sample code. just
highlighting those.


(1) superclass in package A and subclass in package B. try default member
(2) superclass in package A and subclass in package B. try protected
member
(3) try accessing a default member (defined in package A ) in package B.
(4) try accessing a protected member (defined in package A ) in package B.

I have my own understanding for above.
default is 'public' in same package and 'private' in all other packages.
protected is just protected regardless of any package.

Gyan Shankar
Ranch Hand

Joined: Dec 12,
2005
Posts: 65
posted Saturday, December 24, 2005 15:37



I know what default means. only accessible in the same package
I am just asking why do boooks say protected is more accessible than
default even though as per my example shows that protected can only be
accessible to subclasses but default has no such restriction.

So... they are really not more accessible or more restrictive.
On certain situations default is more accessible but in other siutations
protected is more accessible.



Naresh Gunda
Ranch Hand

Joined: Oct 15,
2005
Posts: 163
posted Saturday, December 24, 2005 17:14




This code wont work if int a = 10 is made protected

view plaincopy to clipboardprint?
1. package cert;
2. public class Parent
3. {
4. protected int a = 10;
5. }



Hi jeff,
Even if a has protected access in Parent class,the given program will work
and gives output 10.



Why is default more restrictive than protected?


Yes, default is more restrictive than protected.
'default' members can be accessed by the otherclasses in the same package
only.

'protected' members can be accessed by the otherclasses in the same
package
+
subclasses in any package.

Hence 'default' is more restricted than protected.

Gyan Shankar
Ranch Hand

Joined: Dec 12,
2005
Posts: 65
posted Saturday, December 24, 2005 19:18



I have posted after trying the code
It wont even compile if a is made protected. Please try again.

You can only access a protected variable via inheritance and not via
reference variable.



Naresh Gunda
Ranch Hand

Joined: Oct 15,
2005
Posts: 163
posted Saturday, December 24, 2005 21:25



Hi Jeff, I hv executed this program. Output 10

view plaincopy to clipboardprint?

1.
2. //Parent.java
3. package cert;
4. public class Parent
5. {
6. protected int a = 10;
7. }

view plaincopy to clipboardprint?
1. //Child.java
2. package cert;
3. public class Child
4. {
5. public int useParent()
6. {
7. Parent p = new Parent();
8. return p.a;
9. }
10. }

view plaincopy to clipboardprint?
1.
2. //Use.java
3. import cert.Parent;
4. import cert.Child;
5. public class Use
6. {
7. public static void main(String[] args)
8. {
9. Child c = new Child();
10. System.out.println(c.useParent());
11. }
12. }


Output: 10



You can only access a protected variable via inheritance and not via reference
variable


Sub class can access super class protected member through inheritance
only. and not via superclass variable.
If the child class method uses superclass reference to access the superclass
protected member, it will be compilation error.

In the given program extends class is not used, so there is no
parent child relation between the classes 'Parent' and 'Child'.

Use class main method is calling 'useParent()' (public)method of 'Child'
class.
UseParent() method is accessing 'a' (protected member) in 'Parent' class,
there is no compilation error because, both the classes 'Parent','Child' both
are in same package 'cert'.
A protected member can be accessed by any class in the same package.
[ December 24, 2005: Message edited by: Naresh Kumar ]

Gyan Shankar
Ranch Hand

Joined: Dec 12,
2005
Posts: 65
posted Sunday, December 25, 2005 04:44



You are right.
It was my mistake.

Thanks for clearing my doubt





I agree. Here's the link: http://learnnowonline.com/learnjavanow


subject: default vs protected access




Similar Threads
inheritance of protected attribute

basic java question...please advice

Confused on protected modifier

protected class?

Rules for Protected and Default Members

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:56:13.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton


more from paul wheaton's glorious empire of web junk: cast iron
skilletdiatomaceous earth rocket mass heatersepp holzer raised garden
beds raising chickens lawn care light bulbs flea controlmissoula electric
heaters permaculture


A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this
week in the Web Services forum!

JavaRanch Java Forums Professional Certification Programmer
Certification (SCJP/OCPJP)


Author
Rules for Protected and Default
Members
Brian Reindel
Greenhorn

Joined: Jan 04,
2007
Posts: 6
posted Friday, January 05, 2007 08:10


I am jotting down notes while studying for the SCJP exam, and I want to be
sure that I get this concept 100%. Would it be correct to make the following
two statements:

"A default member of a public class can only be accessed by a class or a
subclass within the same package."

"A protected member of a class can be inherited by a subclass in a different
package, but it cannot be referenced."

If this is not completely correct, or you have alternate ways of stating these
two rules, please let me know.

Thanks
marc weber
Sheriff

Joined: Aug 31,
2004
Posts: 11325
I like...

posted Friday, January 05, 2007 08:29


Welcome to JavaRanch!

I'm moving this to our SCJP forum for special attention. (See links at top of
page to continue discussion there.)


"We're kind of on the level of crossword puzzle writers... And no one ever goes
to them and gives them an award." ~Joe Strummer
sscce.org

qunfeng wang
Ranch Hand

Joined: Jan 28,
2005
Posts: 375
posted Friday, January 05, 2007 08:37



I think you are right.

There is a good explanation in Ch1 of K&B's book.



To be or not to be. It's a question.

Priya Viswam
Ranch Hand

Joined: Dec 28,
2006
Posts: 81
posted Friday, January 05, 2007 08:49



>>"A protected member of a class can be inherited by a subclass in a
different package, but it cannot be referenced."

Protected member can be referenced in the subclass even if the subclass is
in a different package.



SCJP 1.5<br />SCWCD 1.4

Brian Reindel
Greenhorn

Joined: Jan 04,
2007
Posts: 6
posted Friday, January 05, 2007 09:18



Originally posted by Priya Viswam:
>>"A protected member of a class can be inherited by a subclass in a
different package, but it cannot be referenced."

Protected member can be referenced in the subclass even if the subclass is in
a different package.


Priya, if what you say is correct, then why in the book, does this cause an
error:
view plaincopy to clipboardprint?
1. package certification;
2. public class Parent {
3. protected int x = 9;
4. }
5.
6. package other;
7. import certification.Parent
8. class Child extends Parent {
9. public void testIt() {
10. System.out.println(x); // no error - inheritence
11. Parent p = new Parent();
12. System.out.println(p.x); // error - reference!

13. }
14. }

[ January 04, 2007: Message edited by: Brian Reindel ]

Priya Viswam
Ranch Hand

Joined: Dec 28,
2006
Posts: 81
posted Friday, January 05, 2007 09:41



The example shown by you is correct.

From the statement "A protected member of a class can be inherited by a
subclass in a different package, but it cannot be referenced.""
what i understood is that you can't access the protected variable in the
subclass.

If you are using a reference of the parent class then it is not inheritance.
That is the reason why you can't access that in your child class.



Harish
Paravasthu
Greenhorn

Joined: Dec 21,
2006
Posts: 23
posted Friday, January 05, 2007 11:29



Yes priya is right,Protected member in one package can be accssed in other
package only by inheritance and not by reference of suerclass...

harish



Harish Paravasthu

Brian Reindel
Greenhorn

Joined: Jan 04,
2007
Posts: 6
posted Friday, January 05, 2007 19:51



Originally posted by Harish Paravasthu:
Yes priya is right,Protected member in one package can be accssed in other
package only by inheritance and not by reference of suerclass...

harish



Which would mean that my original two statements are correct.

Thank you for everyone's response and for the assistance.



okay, here's the link: http://aspose.com/file-tools


subject: Rules for Protected and Default Members




Similar Threads
Old Chestnut: Protected Access

Protected Scope

Whizlab question

Is Protected Method is accessible?

Rules for Protected and Default Members

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:56:46.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton


more from paul wheaton's glorious empire of web junk: cast iron
skilletdiatomaceous earth rocket mass heatersepp holzer raised garden
beds raising chickens lawn care light bulbs flea controlmissoula electric
heaters permaculture

JProfiler
Get rid of your performance problems and memory leaks!

A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this
week in the Web Services forum!

JavaRanch Java Forums Professional Certification Programmer
Certification (SCJP/OCPJP)


Author
Is Protected Method is
accessible?
Kiran Chand
Panga
Ranch Hand

Joined: Feb 02,
2006
Posts: 31
posted Friday, February 10, 2006 16:10


package testpkg.p1;
public class ParentUtil
{
public int x = 420;
protected int dostuff()
{
return x;
}
}



package testpkg.p2;
import testing.p1.ParentUtil;
public class ChildUtil extends ParentUtil
{
public static void main(String[] agrs)
{
new ChildUtil.callStuff();
}

void callStuff()
{
System.out.println("this"+this.dostuff());
ParentUtil p = new ParenUtil();
System.out.println("parent"+p.dostuff());//Ans: Error In this line
}
}

Can any one tell why it will show error? Cant we access the protected
member or method from which class extends the other class which is in
different package?


Thanks & Regards <br /> <br />Kiran Chand Panga<br />SCJP1.4

brindha m.
Greenhorn

Joined: Feb 09,
2006
Posts: 1
posted Friday, February 10, 2006 16:51



Hi Kiran,

When u call this.doStuff() u are calling the inherited protected
member.Since the ChildUtil class is a subclass of ParentUtil class the
method is inherited.

But in case of calling doStuff() with the parent class reference, u can access
only the public members.
Protected members are accessbile only within the same package and in their

subclasses even in different package) only.

Check this link to know more about accessbility.
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html

Hope this helps.

Brindha.

Anju sethi
Ranch Hand

Joined: Dec 26,
2005
Posts: 91
posted Friday, February 10, 2006 17:03



Remember, protected access modifier always refers to <package + kids >.
that means this modifier is accessible to subclass outside package only thru
inheritence.

It is illegal to make an instance of superclass and access protected member
outside package as protected member would act as private or default to this
instance.
Also, protected member is inherited by derived class outside package and
not by any other subclass of the derived class.
it becomes private in the subclass outside package.

Please concentrate on rules of protected modifier outside package



thanks,<br />Anju Sethi

srilatha
kareddy
Ranch Hand

Joined: Jan 12,
2006
Posts: 32
posted Friday, February 10, 2006 21:02



hi Kiran Chand ,

here is the example to understand the concept

package testpkg.p2;
import testing.p1.ParentUtil;

public class ChildUtil extends ParentUtil
{
public static void main(String[] agrs)
{
ChildUtil child= new ChildUtil();
ParentUtil parent= new ParentUtil();

child.protectedMehtod();....we can do it
parent.protectedField; ...possible
parent.protectedMethod();///ERROR
parent.protectedField; //ERROR
}

}

this means through child class reference can have access to protected
members but not through parent class reference. This is the reason why we
use protected keyword



I agree. Here's the link: http://ej-technologies/jprofiler


subject: Is Protected Method is accessible?




Similar Threads
Confused in Access control topic

protected access modifier

A ques's answer explanation not correct in K&B in chap 2

confused

protected access question

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:57:13.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton


more from paul wheaton's glorious empire of web junk: cast iron
skilletdiatomaceous earth rocket mass heatersepp holzer raised garden
beds raising chickens lawn care light bulbs flea controlmissoula electric
heaters permaculture

A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in
Action this week in the Web
Services forum!

JavaRanch Java Forums Professional
Certification Programmer Certification (SCJP/OCPJP)


Author
protected access modifier
Puja S
Ranch Hand

Joined: Jan 06,
2005
Posts: 51
posted Sunday, January 23, 2005 02:56


Hi,

package testpkg.p1;
public class ParentUtil {
public int x = 420;
protected int doStuff() { return x; }
}

package testpkg.p2;
import testpkg.p1.ParentUtil;
public class ChildUtil extends ParentUtil {
public static void main(String [] args) {
new ChildUtil().callStuff();
}
void callStuff() {
System.out.print("this " + this.doStuff() );
ParentUtil p = new ParentUtil();
System.out.print(" parent " + p.doStuff() );
}
}

which statement is true?

1. The code compiles and runs, with output this 420 parent 420.

2.If line 8 is removed, the code will compile and run.

3.If line 10 is removed, the code will compile and run.

4.Both lines 8 and 10 must be removed for the code to compile.

5.An exception is thrown at runtime.


The answer ios 3....Why? Can anybody explain me. I thought the
answer was 1.

Thanks.
Mike
Gershman
posted Sunday, January 23, 2005 03:10

Ranch Hand

Joined: Mar 13,
2004
Posts: 1272

In order to acess a protected member of a superclass that is in
another package, you must use a reference type of your class or
a subclass of your class. So this was OK, because it is of type
ChildUtil, but p is not OK because it is of type ParentUtil.


Mike Gershman
SCJP 1.4, SCWCD in process

Puja S
Ranch Hand

Joined: Jan 06,
2005
Posts: 51
posted Sunday, January 23, 2005 03:17



Thanks Mike,
You said "You must use a reference of your class or a subclass of
your class to access the protected member".......I am not able to
understand how a subclass of the class can be used.Please can
you give me an example.

Thanks



Puja S
Ranch Hand

Joined: Jan 06,
2005
Posts: 51
posted Sunday, January 23, 2005 08:59



Thanks Mike........I understood the concept.



meena latha
Ranch Hand

Joined: Jan 24,
2005
Posts: 219
posted Tuesday, January 25, 2005 02:59



Hi ............i am clear about the concept can any one of you
please explain to me.





I agree. Here's the link: http://ej-technologies/jprofiler


subject: protected access modifier




Similar Threads
Confused in Access control topic

A ques's answer explanation not correct in K&B in chap 2

confused

Is Protected Method is accessible?

protected access question

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:57:29.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton


more from paul wheaton's glorious empire of web junk: cast iron
skilletdiatomaceous earth rocket mass heatersepp holzer raised garden
beds raising chickens lawn care light bulbs flea controlmissoula electric
heaters permaculture


A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this week in the Web
Services forum!

JavaRanch Java Forums Professional Certification Programmer Certification
(SCJP/OCPJP)


Author
A ques's answer explanation not correct in
K&B in chap 2
Amit Das
Ranch Hand

Joined: Mar 05,
2005
Posts: 206
posted Friday, April 29, 2005 01:31


hi all,

K&B chap 2 page 136 ques 6:

Given the following,
view plaincopy to clipboardprint?
1. 1. package testpkg.p1;
2. 2. public class ParentUtil {
3. 3. public int x = 420;
4. 4. protected int doStuff() { return x; }
5. 5. }
6.
7. 1. package testpkg.p2;
8. 2. import testpkg.p1.ParentUtil;
9. 3. public class ChildUtil extends ParentUtil {
10. 4. public static void main(String [] args) {
11. 5. new ChildUtil().callStuff();
12. 6. }
13. 7. void callStuff() {
14. 8. System.out.print("this " + this.doStuff() );
15. 9. ParentUtil p = new ParentUtil();
16. 10. System.out.print(" parent " + p.doStuff() );
17. 11. }
18. 12. }

which statement is true?
A. The code compiles and runs, with output this 420 parent 420.
B. If line 8 is removed, the code will compile and run.
C. If line 10 is removed, the code will compile and run.
D. Both lines 8 and 10 must be removed for the code to compile.
E. An exception is thrown at runtime.

well undoubtedly the answer is c as a subclass outside the pacakge of the superclass can access the
protected member only by inheritance i.e. it can only access them by object reference of type the sub
class.

the explanation given says:
view plaincopy to clipboardprint?
1. 1. package testpkg.p1;
2. 2. public class ParentUtil {
3. 3. public int x = 420;
4. 4. protected int doStuff() { return x; }
5. 5. }
6. 1. package testpkg.p2;
7. 2. import testpkg.p1.ParentUtil;
8. 3. public class ChildUtil extends ParentUtil {
9. 4. public static void main(String [] args) {
10. 5. new ChildUtil().callStuff();
11. 6. }
12. 7. void callStuff() {
13. 8. System.out.print("this " + this.doStuff() );
14. 9. [B]ParentUtil p = new ChildUtil(); //MAKE A NOTE[/B]
15. 10. if( p instanceof ChildUtil)
16. 10. System.out.print(" parent " + p.doStuff() ); //compilation error
17. 11. }
18. 12. }


now if we go according to its explanation that

doStuff() can be accessed only by instances of the ChildUtil class


p should have accessed the protected member as its an instance of the class ChildClass.

in my opnion, the reference type used for such an acces should be of type subclassor its further
subclasses.

plz verify my thought, i'll be deeply obliged.

thanx
amit

[edited because unindented code is too painful to read - Jim]
[ April 28, 2005: Message edited by: Jim Yingst ]
Joe Sondow
Ranch Hand

Joined: Apr 10,
2005
Posts: 195
posted Friday, April 29, 2005 02:07


You are right that their explanation was not totally complete. You showed a counterexample where
doStuff() appears to be getting accessed by an instance of ChildUtil, but it does not compile because p
is a ParentUtil reference. Since p.doStuff() is not a legal call from within ChildUtil, you get a compiler
error.

Here's the tricky part: the compiler doesn't know or care that p actually references a ChildUtil
object. All the compiler knows or cares about is that p is a reference to a ParentUtil, and calling the
doStuff() method on a ParentUtil is not legal from that point in the code. It looks like it should work
because of polymorphism, but actually polymorphism doesn't apply here because you're not allowed to
make the call p.doStuff() at all, regardless of what p actually references.

What I suspect the authors meant by "doStuff() can be accessed only by instances of the ChildUtil
class" was that you would need an instance of ChildUtil that is being referenced by a
ChildUtil reference as well. They simply neglected to point out the case you presented, where the
reference type differs from the instance type.
[ April 28, 2005: Message edited by: Joe Sanowitz ]

SCJA 1.0 (98%), SCJP 1.4 (98%)

Saranyan
Narayanan
Ranch Hand

Joined: Mar 12,
2003
Posts: 34
posted Friday, April 29, 2005 14:38



Joe could we say this:

When a protected member is accessed in a subclass using a parent class reference , it cannot let the
polymorphic call compile as the protected member in the overriding class is private to the subclass.



Joe Sondow
Ranch Hand

posted Friday, April 29, 2005 18:51



Joined: Apr 10,
2005
Posts: 195
Originally posted by Saranyan Narayanan:
Joe could we say this:

When a protected member is accessed in a subclass using a parent class reference , it cannot let the
polymorphic call compile as the protected member in the overriding class is private to the subclass.


Careful with the terms "overriding" and "overridden". People often confuse them. The overriding
method is the one in the subclass that overrides the original parent method. The overridden method is
the original parent method that the child has replaced (overridden) with a new version.

Anyway, in the examples Amit Das posted, there is no overriding. Subclassing is not the same thing as
overriding. You can override an accessible method, but you cannot override a class.

I wouldn't say "When a protected member is accessed in a subclass using a parent class reference..."
Instead I would say:

If the child class and parent class are in different packages, a protected member of the
parent class cannot be accessed in the child class by using a parent class reference.

While you're getting on the right track in your thinking, it's not really correct to say that the method is
"private to the subclass", since "private" has a distinct meaning. I prefer the word "inaccessible". The
method is inaccessible to the subclass. I also wouldn't say "it cannot let the polymorphic call compile"
because there is no polymorphic call here. Polymorphic calls are possible only when you can invoke the
method on the parent reference. Since p.doStuff() is not legal in this situation, it's simper and more
accurate to state the rule as I did in bold in the previous paragraph. Here's the rule again with sub- and
super- terminology if you prefer:

If the subclass and superclass are in different packages, a protected member of the
superclass cannot be accessed in the subclass by using a superclass reference.





I agree. Here's the link: http://ej-technologies/jprofiler


subject: A ques's answer explanation not correct in K&B in chap 2




Similar Threads
protected access modifier

Confused in Access control topic

confused

Is Protected Method is accessible?

protected access question

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:57:44.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton


more from paul wheaton's glorious empire of web junk: cast iron
skilletdiatomaceous earth rocket mass heatersepp holzer raised garden
beds raising chickens lawn care light bulbs flea controlmissoula electric
heaters permaculture

This week's book giveaway is in the Web Services forum.
We're giving away four copies of Restlet in Action and have
Jerome Louvel, Thierry Templier, and Thierry Boileau on-line!
See this thread for details.

A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this
week in the Web Services forum!

JavaRanch Java Forums Professional Certification Programmer
Certification (SCJP/OCPJP)


Author
Is Protected Method is
accessible?
Kiran Chand
Panga
Ranch Hand

Joined: Feb 02,
2006
Posts: 31
posted Friday, February 10, 2006 16:10


package testpkg.p1;
public class ParentUtil
{
public int x = 420;
protected int dostuff()
{
return x;
}
}



package testpkg.p2;
import testing.p1.ParentUtil;
public class ChildUtil extends ParentUtil
{
public static void main(String[] agrs)
{
new ChildUtil.callStuff();
}

void callStuff()
{
System.out.println("this"+this.dostuff());
ParentUtil p = new ParenUtil();
System.out.println("parent"+p.dostuff());//Ans: Error In this line
}
}

Can any one tell why it will show error? Cant we access the protected
member or method from which class extends the other class which is in
different package?


Thanks & Regards <br /> <br />Kiran Chand Panga<br />SCJP1.4

brindha m.
Greenhorn

Joined: Feb 09,
2006
Posts: 1
posted Friday, February 10, 2006 16:51



Hi Kiran,

When u call this.doStuff() u are calling the inherited protected
member.Since the ChildUtil class is a subclass of ParentUtil class the
method is inherited.

But in case of calling doStuff() with the parent class reference, u can access
only the public members.
Protected members are accessbile only within the same package and in their
subclasses even in different package) only.

Check this link to know more about accessbility.

http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html

Hope this helps.

Brindha.

Anju sethi
Ranch Hand

Joined: Dec 26,
2005
Posts: 91
posted Friday, February 10, 2006 17:03



Remember, protected access modifier always refers to <package + kids >.
that means this modifier is accessible to subclass outside package only thru
inheritence.

It is illegal to make an instance of superclass and access protected member
outside package as protected member would act as private or default to this
instance.
Also, protected member is inherited by derived class outside package and
not by any other subclass of the derived class.
it becomes private in the subclass outside package.

Please concentrate on rules of protected modifier outside package



thanks,<br />Anju Sethi

srilatha
kareddy
Ranch Hand

Joined: Jan 12,
2006
Posts: 32
posted Friday, February 10, 2006 21:02



hi Kiran Chand ,

here is the example to understand the concept

package testpkg.p2;
import testing.p1.ParentUtil;
public class ChildUtil extends ParentUtil
{
public static void main(String[] agrs)

{
ChildUtil child= new ChildUtil();
ParentUtil parent= new ParentUtil();

child.protectedMehtod();....we can do it
parent.protectedField; ...possible
parent.protectedMethod();///ERROR
parent.protectedField; //ERROR
}

}

this means through child class reference can have access to protected
members but not through parent class reference. This is the reason why we
use protected keyword



I agree. Here's the link: http://learnnowonline.com/learnjavanow


subject: Is Protected Method is accessible?




Similar Threads
protected access modifier

Confused in Access control topic

A ques's answer explanation not correct in K&B in chap 2

confused

protected access question

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:57:59.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton


more from paul wheaton's glorious empire of web junk: cast iron
skilletdiatomaceous earth rocket mass heatersepp holzer raised garden
beds raising chickens lawn care light bulbs flea controlmissoula electric
heaters permaculture


A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this
week in the Web Services forum!

JavaRanch Java Forums Professional Certification Programmer
Certification (SCJP/OCPJP)


Author
Confused in Access control topic
Adil El mouden
Ranch Hand

Joined: Jun 01,
2005
Posts: 82
posted Sunday, August 07, 2005 17:37


Hi,
This is a question from K&B book:

Given the following,
view plaincopy to clipboardprint?
1. 1. package testpkg.p1;
2. 2. public class ParentUtil {
3. 3. public int x = 420;
4. 4. protected int doStuff() { return x; }
5. 5. }
6.
7. 1. package testpkg.p2;
8. 2. import testpkg.p1.ParentUtil;
9. 3. public class ChildUtil extends ParentUtil {
10. 4. public static void main(String [] args) {
11. 5. new ChildUtil().callStuff();
12. 6. }
13. 7. void callStuff() {
14. 8. System.out.print("this " + this.doStuff() );
15. 9. ParentUtil p = new ParentUtil();
16. 10. System.out.print(" parent " + p.doStuff() );
17. 11. }
18. 12.}


which statement is true?
A. The code compiles and runs, with output this 420 parent 420.
B. If line 8 is removed, the code will compile and run.
C. If line 10 is removed, the code will compile and run.
D. Both lines 8 and 10 must be removed for the code to compile.
E. An exception is thrown at runtime.

Answer given: C
I didn't understand the fact that p in line 10 cannot invoke its doStuff()
method.

Thank you.

(formatted code)

[ August 07, 2005: Message edited by: Barry Gaunt ]
[ August 07, 2005: Message edited by: Adil El mouden ]

SCWCD 1.4(Loading...), SCJP 1.4(98%), Bachelor of Engineering (computer
science)

Priya dharshini
posted Sunday, August 07, 2005 18:00

Ranch Hand

Joined: Aug 06,
2005
Posts: 78


The subclasses outside the package can't use a superclass reference to
access a protected member. For a subclass outside the package, the
protected member can be accessed only thr' inheritance.

The ParentUtil instance p cannot be used to access the doStuff()
method.Because dostuff() has protected access, and the ChildUtil class is
not in the same package as the ParentUtil class.doStuff()can be accessed
only by instance of the ChildUtil class(a subclass of ParentUtil).



Thanks & Regards,
Priyadharshini . T

Barry Gaunt
Ranch Hand

Joined: Aug 03,
2002
Posts: 7729
posted Sunday, August 07, 2005 18:05



See the example in the Java Language Specification (JLS) 3.0 section
6.6.7 here.



Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just
telling them the answer.



okay, here's the link: http://aspose.com/file-tools


subject: Confused in Access control topic




Similar Threads
protected access modifier

A ques's answer explanation not correct in K&B in chap 2

confused

Is Protected Method is accessible?

protected access question

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:58:11.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton

more from paul wheaton's glorious empire of web junk: cast iron
skillet diatomaceous earth rocket mass heater sepp holzerraised
garden beds raising chickens lawn care light bulbs flea
control missoulaelectric heaters permaculture

JProfiler
Get rid of your performance problems and memory leaks!

A friendly
place for
programming
greenhorns!
Big Moose Saloon
Search | Java FAQ | Recent Topics
Register / Login

Win a copy of Restlet in Action this
week in the Web Services forum!

JavaRanch Java Forums Java Java in General


Author
protected access question
Kenny Johnson
posted Wednesday, January 03, 2007 06:40
Ranch Hand

Joined: Jan 01,
2007
Posts: 37


view plaincopy to clipboardprint?
1. package testpkg.p1;
2. public class ParentUtil {
3. public int x = 420;
4. protected int doStuff() { return x; }
5. }
6.
7. package testpkg.p2;
8. import testpkg.p1.ParentUtil;
9. public class ChildUtil extends ParentUtil {
10. public static void main(String [] args) {
11. new ChildUtil().callStuff();
12. }
13. void callStuff() {
14. System.out.print("this " + this.doStuff() );
15. ParentUtil p = new ParentUtil();
16. System.out.print(" parent " + p.doStuff() );
17. }
18. }


How come in the ChildUtil class that extends ParentUtil, I cant call the
protected method of ParentUtil. Protected access states that you have to be
either in the same package or a child class to use protected variables /
methods. Can someone please explain where I am going wrong?


I agree. Here's the link: http://learnnowonline.com/learnjavanow

subject: protected access question


Similar Threads
protected access modifier

Confused in Access control topic

A ques's answer explanation not correct in K&B in chap 2

confused

Is Protected Method is accessible?

All times above are in your local time zone & format.The current ranch time (not your local time) is Dec 05, 2012 05:58:27.


Contact Us | Powered by JForum | Copyright 1998-2012 Paul Wheaton


more from paul wheaton's glorious empire of web junk: cast iron
skilletdiatomaceous earth rocket mass heatersepp holzer raised garden
beds raising chickens lawn care light bulbs flea controlmissoula electric
heaters permaculture

You might also like