Friday, 6 September 2013

Using an arbitrarily defined method of an anonymous interface

Using an arbitrarily defined method of an anonymous interface

Consider the following code:
public static void main(String[] args) {
File file = new File("C:\\someFile.txt") {
public void doStuff() {
// Do some stuff
}
};
file.doStuff(); // "Cannot resolve method"
}
When we try to call our newly defined method doStuff(), it isn't possible.
The reason for this is that file is defined as an object of type File and
not as an instance of our new, anonymous override.
So, my question is, is there any 'nice' way to achieve this behaviour?
Other than the obvious (which is to just, declare the class properly).

No comments:

Post a Comment