This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected and anynomous class

 
Bin Wang
Ranch Hand
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assume we have the following code in the file abc/Q.java:
// File: abc/Q.java
package abc;
public class Q {
protected int protectedVar;
}
and this code is in the default package:
// File: Tester.java
import abc.Q;
public class Tester {
private Q q = new Q() {
void someMethod() {
protectedVar = 1; // will this compile?
}
};
}
Determine whether or not the assignment statement in Tester will compile successfully. Assume the directory, /abc, is in the compiler's CLASSPATH.
The program does compile. But my question is: although you can assign the protected variable (protectedVar) within the anonymous class, there is no way to retrieve it within the Tester class, is that right?
 
Ranjan Chaudhuri
Ranch Hand
Posts: 33
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure what you mean. If you added a method to the Tester
class, you could retrieve the relevant variable, e.g.
---------------------
void changeVal() {
q.protectedVar = 2;
}
----------------------
That would change the value of that variable, because it was declared in class Q, and q has access to it.
There's no way to call someMethod() though, I don't think, because you can't cast q to the anonymous class.
Not sure what your question is, so sorry if I'm failing to address it.
 
Bin Wang
Ranch Hand
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ranjan,
I add the following method in Tester class:
void changeVal() {
q.protectedVar = 2;
}
and got the compile error: Variable protectedVar in abc.Q not accessible from class Tester.
I think that's my point.
 
Ranjan Chaudhuri
Ranch Hand
Posts: 33
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bin, you're right. I didn't look at it too carefully. The classes are in different packages. The import statement gives access to the name of the class but not its contents. Sorry.
If the classes were in the same package (directory), then it would work as I was suggesting.
It's a good question.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic