This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on apckage Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on apckage " Watch "Question on apckage " New topic
Author

Question on apckage

Dinesh Tahiliani
Ranch Hand

Joined: Aug 06, 2007
Posts: 486
package p1;
public class A {
protected int i = 10;
public int getI() { return i; }
}

package p2;
public class B extends p1.A {
public void process(A a)
{ a.i = a.i*2; }
public static void main(String[] args)
{
A a = new B();
B b = new B();
b.process(a);
System.out.println( a.getI() );
}
}


Giving error on i . Please explain
My own cde


Thanks<br />Dinesh
Luciano Queiroz
Ranch Hand

Joined: Feb 04, 2002
Posts: 172
It's clear!

First of all, you must write:

import p1.A;


Second, you can not access i through A.
You must access i only by inheritance, that is, you must type i directly inside class B.

Ex.:


package p2;

import p1.A;

public class B extends p1.A
{
public void process(A a)
{
i = i*2;
}

public static void main(String[] args)
{
A a = new B();
B b = new B();
b.process(a);
System.out.println( a.getI() );
}
}


But in this case, the output will be "10".


<b>Luciano Queiroz</b><br/>
 Brazil<br/>
 <i>SCJP 1.2, SCWCD, IBM 141, IBM 483, SCJP 1.4, IBM 484, IBM 287, SCBCD, SCEA, SCJP 5.0, SCJP 6.0, SCWCD 5</i>
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13884
    
  10

You mean: This gives a compile error in the method process(A a) in class B.

This is one of the peculiarities of how 'protected' works. When a field is 'protected', it is visible in subclasses and in classes of the same package; but only the field of the object itself is visible. In this example, you are looking at field 'i' of a different object - and then it's not visible.

Section 6.6.2 of The Java Language Specification explains this (with just a very short sentence):
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.


Note: Please use code tags when you post source code.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question on apckage
 
Similar Threads
Inheriting Protected Variables
why compile time error???
please answer the question and explain it to me,thanks!
Compile or not?
How does this work ?