问题
public class ABC extends XYZ
{
public static class InnerClass1
{
...
}
public static class InnerClass2
{
...
}
public static class InnerClass3
{
...
}
public static class InnerClass4
{
...
}
}
In the above code, I cannot access the methods of the class XYZ inside the inner classes1,2,3 and 4. How can i modify the above structure so that the inner classes can access the methods within the class XYZ ?
Thanks in advance !
回答1:
public class ABC extends XYZ
{
public static class InnerClass1
{
...
}
InnerClass1
is not an inner class. It's a nested class, because of the word static
.
If there were no static
, it would be an inner class. And any instance of that inner class would have a hidden reference to an ABC
(which is also an XYZ
). If the inner class called any instance methods of ABC
or XYZ
, or referred to any instance variables in those classes, it would use that hidden reference to call the instance methods or access the instance variables.
Since it's a nested class, though, there is no hidden reference to an ABC
(or XYZ
). Thus, if you call an instance method or refer to an instance variable, it can't do it, because there is no ABC
object to work with. (However, you can still call a static method of an ABC
, or refer to a static variable.)
I'm not sure what the solution is--it depends on your needs. It's possible that the XYZ
methods you can't call don't actually need an XYZ
object to work on, and therefore those methods should be static. It's also possible that the nested class should have some explicit ABC
or XYZ
variable that it uses to access the instance methods; you can still call instance methods from a nested class if you have an object to work on:
public static class NestedClass {
XYZ x;
void someMethod() {
x.instanceMethod(); // legal even if instanceMethod is non-static
}
}
The other solution would be to remove the word static
, so that InnerClass1
really has a hidden reference to an ABC
. This means that when you create an InnerClass1
instance, you need some ABC
object for it to refer to. If you create this in some other class, the syntax would be something like
ABC abcObject;
...
ABC.InnerClass1 newObject = abcObject.new InnerClass1();
回答2:
static inner class can only access static members of the outer class
so the inner class will only be able to use the static members of xyz.
create the inner class non static if you want to access everything
回答3:
You have two options, one remove the static call so a hidden this reference to the outer class is available to the inner class instances or two, when you create an instance of the inner class pass in a this explicitly, example:
public class ABC extends XYZ
{
XYZ.InnerClass innerInst = new InnerClass(this);
public static class InnerClass1
{
private final ABC extref;
public void Innerclass(ABC outerref)
{
extref = outerref;
}
...
}
}
来源:https://stackoverflow.com/questions/27339664/accessing-methods-of-extended-class-from-inner-class