File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes protected and anynomous class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "protected and anynomous class" Watch "protected and anynomous class" New topic
Author

protected and anynomous class

Bin Wang
Ranch Hand

Joined: May 01, 2001
Posts: 82
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

Joined: May 22, 2001
Posts: 33
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

Joined: May 01, 2001
Posts: 82
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

Joined: May 22, 2001
Posts: 33
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
 
subject: protected and anynomous class