This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes How does this work ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How does this work ?" Watch "How does this work ?" New topic
Author

How does this work ?

sachin jauhari
Greenhorn

Joined: Jul 14, 2005
Posts: 15
Why does the following give compilation error at line 1.
Class B extends Class A which is in a different package.

//in file A.java
package p1;
public class A
{
protected int i = 10;
public int getI() { return i; }
}

//in file B.java
package p2;
import p1.*;
public class B extends p1.A
{
public void process(A a)
{
a.i = a.i*2; // line 1
}
public static void main(String[] args)
{
A a = new B();
B b = new B();
b.process(a);
System.out.println(a.getI());
}
}
Brijesh Dinkar
Greenhorn

Joined: May 20, 2005
Posts: 15
when you are accessing the variable 'i', you are not making use of inheritance, hence the problem.The protected variable 'i' will not be visible to classes outside the pacakge unless you make use of inheritance.
So somethin like this will work-
package p1;
public class A
{
protected int i = 10;
public int getI() { return i; }
}

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

Hope this helps!

Brijesh
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How does this work ?
 
Similar Threads
please answer the question and explain it to me,thanks!
Compile or not?
question from JQ+
why compile time error???
mock test question on protected access specifier