I want to define my property and function in anonymous class as under
ExistingExtendableJavaClass aClass = new ExistingExtendableJavaClass() {
public String someProperty;
public String getMyProperty() { return someProperty }
});
But then these calls don't work
aClass.someProperty // not accessible
aClass.getMyProperty() // not accessible
I know because ExistingExtendableJavaClass
doesn't have these, but then my anonymous has these. How can I achieve this ?
They are accessible just fine:
new ExistingExtendable() {
public void foo() {}
}.foo();
works great.
But if you write:
ExistingExtendable x = new ExistingExtendable() {
public void foo() {}
};
x.foo();
That does not work. For the same reason this doesn't work:
Object o = new String();
o.toLowerCase(); // nope
The problem is that your anonymous class has no name, thus, you cannot denote its type. We can fix the string example by replacing Object o
with String o
, but there is no String
equivalent.
However, that is the point of an anonymous inner class.
If you want these to be denotable, then you don't want an anonymous inner class. Asking: "I want an anonymous inner class, but I want the new members I declared in them to be accessible" is like asking: "I want a circle, but.. with corners".
You can make method local inner classes, and now you have names:
public void example(String x) {
class IAmAMethodLocalClass extends ExistingExtendableJavaClass {
String someProperty; // making them public is quite useless.
String foo() {
System.out.println(x); // you can access x here.
}
}
IAmAMethodLocalClass hello = new IAmAMethodLocalClass();
hello.someProperty = "It works!";
}
an anonymous inner class is the same as this method local class thing, except it avoids naming the type. In this case, you NEED that name, thus, you can't use the anonymous inner class construct.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments