The short form of the question is:
- abstract class A1
- abstract class A2 that creates an anonymous inner A1
- Class A3 extends A2 - can an instance of A1 created by A2 know it was created within A3?
Fleshing out the question:
Lets say i have an abstract class:
public abstract class Abstract1 {}
Then I have a second abstract class that can create instances of Abstract1:
public abstract class Abstract2 {
protected Abstract1 createAbstract1() {
return new Abstract1() {};
}
}
Third, I have a concrete implementation of Abstract2:
public class Concrete extends Abstract2 {}
Lets put some print statements into Abstract2:
public abstract class Abstract2 {
public Abstract1 createAbstract1() {
System.out.println("I am: " + getClass().getName());
Abstract1 a1 = new Abstract1() {};
System.out.println("A1 is enclosed by: " + ab1.getClass().getEnclosingClass().getName());
return a1;
}
}
When we construct Concrete
and ask for an A1 as follows...
Concrete charlie = new Concrete();
Abstract1 myA1 = charlie.createAbstract1();
...we see the following output:
I am: Concrete
A1 is enclosed by: Abstract2
How can myA1 know it was created by a Concrete instead of an Abstract2?
Aucun commentaire:
Enregistrer un commentaire