【问题标题】:Can't access members of an anonymous, nested subclass (implementing an interface)无法访问匿名嵌套子类的成员(实现接口)
【发布时间】:2014-12-10 04:09:54
【问题描述】:

我这里有问题。我这样写一段代码:

package vh.Static;

public class Nesting {
    //static class Nested{}
    class Inner{}
    void method(){
        Inner inner = new Inner(){
            public int z =2;
            public int getZ(){
                return z;
            }
        };
        System.out.println(inner);
    }
    public static void main(String args[]){
        Nesting ne  =new Nesting();
        Inner inner = ne.new Inner(){
            public int z =1;
            public int getZ(){
                return z;
            }
        };
        System.out.println(inner);
        ne.method();
   }
}

我不知道如何在 Inner 构造函数块中获取 var z 定义。请帮帮我! 告诉我 z local 在哪里?在内?或嵌套

【问题讨论】:

  • 在你的method()中,返回inner.getZ();
  • 不,它不可用。因为,Inner是空类,实际上没有方法和var

标签: java class interface inner-classes


【解决方案1】:

您问题的原始标题的答案非常广泛 - 您需要做一些研究:

  • Interface 只是合约定义,没有实现
  • 类可以有实现
  • nested class 仅对其包含的类可见

但要解决您的具体示例,请在代码中:

void method(){
    Inner inner = new Inner(){
        public int z =2;
        public int getZ(){
            return z;
        }
    };
}

这会实例化嵌套类Inner 的新匿名子类,然后使用公共字段和方法扩展匿名子类。

无法访问扩展字段+方法的原因是变量inner是基类型Inner(没有添加任何内容 - 这被简单地定义为class Inner{}),并且不是匿名子类的类型。就目前而言,您需要求助于反射等讨厌的东西来访问匿名子类中的字段+属性,在匿名子类本身之外。

 System.out.println(inner.getZ()); // Does not compile

可以做的是在Inner 上定义抽象方法,然后在匿名类中覆盖这些方法:

abstract class Inner{
    public abstract int getZ();
}

void method(){
    Inner inner = new Inner(){
        private int z =2; // Private fields plz, use get / setters
        public int getZ(){
            return z;
        }
    };

您现在可以在Nesting 类中的任何位置访问定义的Inner 方法

关于约定的注意事项 - the docs 将内部类(您的Inner)称为nested class,将外部类(您的Nesting)称为Outer

同样的事情将Inner定义为一个接口,然后匿名实现:

class Nesting {
    interface Inner{
        int getZ();
    }
    void method(){
        Inner inner = new Inner(){
            private int z =2;
            public int getZ(){
                return z;
            }
            private int anotherInnerMethod(){
                // Can access non-interface items as it is part of the anon subclass
                return z * z;
            }
        };
        System.out.println(inner);
        // Access getZ() through the interface
        System.out.println(inner.getZ());
    }
    // Because this method is in class Nesting, it may still access Inner
    public static void main(String args[]){
        Nesting ne = new Nesting();
        ne.method();
        Inner inner = new Inner(){
            private int z =1;
            public int getZ(){
                return z;
            }
        };
        System.out.println(inner.getZ());
        ne.method();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多