简体   繁体   English

如何参考本地课程

[英]How to reference local class

I have a local class... 我有一个本地班......

public class Outer {
    public void wrapper() {
        class Local {
        }
    }
}

and I have a test that needs to reference the local class... 我有一个需要参考当地班级的考试...

Outer.wrapper.Local.class ## this doesn't seem to work

How can I reference the local class? 我怎样才能参考当地的班级?

You can only reference a Local Inner class inside the method in which you have declared it: 您只能在声明它的方法中引用Local Inner类:

public void wrapper() {
  class Local {

  }
  Local obj = new Local();
}

This classes tend to not be very useful due to their limited scope. 由于范围有限,这些类往往不是很有用。 If you have found a valid use case to define one take a look at this tutorial . 如果您找到了一个有效的用例来定义一个,请看一下本教程

Local Class (aka Local Inner Class or Method-Local Inner Class): 本地班级 (又名本地班级或方法 - 本地班级班级):

Local class is defined as an inner class within a method. 本地类被定义为方法中的内部类。 Like local variables, a local inner class declaration does not exist until the method is invoked, and it goes out of scope when the method returns. 与局部变量一样,在调用方法之前,本地内部类声明不存在,并且在方法返回时超出范围。 This means its instance can be created only from within the method it is declared in. 这意味着它的实例只能在声明它的方法中创建。

This inner class can be instantiated only after its definition (ie, the instantiation code must follow the declaration). 此内部类只能在其定义后实例化(即,实例化代码必须遵循声明)。 The inner class do not have access to local variables of the method unless those variables are final or effectively final. 内部类无法访问方法的局部变量,除非这些变量是最终的或有效的最终变量。

Here is an example: 这是一个例子:

int length = 10; // outer class's instance variable

public void calculate() {
    final int width = 20;
    class Inner { // inner class definition
        public void area() {
            System.out.println(length * width);
        }
    }
    Inner local = new Inner(); // this statement comes only after local class's definition
    local.area();
}

NOTES: 笔记:

  • The only modifiers that can be applied to a method-local inner class are abstract and final, but never both at the same time. 可以应用于方法本地内部类的唯一修饰符是abstract和final,但不能同时使用两者。
  • A local class declared within a static method has access to only static members of the enclosing class, and no access to instance variables. 在静态方法中声明的本地类只能访问封闭类的静态成员,并且无权访问实例变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM