java - Extending a non-static class nested in non-baseclass implementing an interface -


first, idealized working example of doing want do:

public final class 1 {     private int i;      public class inone {         public int foo() { return i; }     } }  public class 2 {     private final 1 aone = new one();      object getintwo() {         return aone.new inone() {             public int somemethod() { return foo() + 100; }         };     } } 

fine, can extend non-static class in non-baseclass, qualifying new enclosing instance. of course, stands makes no sense, since somemethod becomes inaccessible in returned object. in actuality, return type of getintwo not supposed object someinterface, defined this:

public interface someinterface {     int somemethod(); } 

as far know, there no way create anonymous class both extends class , implements interface not implemented class. i'll have non-anonymous class, this:

public class 2 {     private final 1 aone = new one();      object getintwo() {         class intwo extends one.inone implements someinterface {             public int somemethod() { return foo() + 100; }         }         return new intwo();     } } 

now compiler tells me enclosing instance contains one.inone required, makes sense, have object want enclosing instance, , in anonymous class case able specify aone.new. can't use anonymous class, can't specify enclosing instance, or can i?

obviously there ways around moving things around in class hierarchy (e.g., encapsulating inone in intwo instead if extending), fine in idealized toy example, in context want messier, asking do. far can see, there nothing structural prevents it, it's syntax problem.

this should work you

public class 2 {    private final 1 aone = new one();     object getintwo() {       class intwo extends one.inone implements someinterface {              public intwo(){                 aone.super();             }             public int somemethod() { return foo() + 100; }        }        return new intwo();     } } 

your problem inner class of one.inone can exist within context of instance of one. therefore, in constructor, must able provide enclosing instance of class extends one.inone.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -