首页 > 代码库 > Javac内部类本地类
Javac内部类本地类
One way declared types in Java differ from one another is whether the type is a class (which includes enums) or an interface (which includes annotation types). An independent property of a type is its relation to the surrounding lexical context.
A top level class does not appear inside another class or interface. If a type is not top level it is nested. However, there are a number of distinct ways a type can be nested. First, a type can be a member of another type; a member type is directly enclosed by another type declaration. All member types have names; however, some member types are inner classes and others are not. If a type is explicitly or implicitly static, it is not an inner class; all member interfaces are implicitly static.
Inner classes also include local classes, which are named classes declared inside of a block like a method or constructor body, and anonymous classes, which are unnamed classes whose instances are created in expressions and statements. Anonymous classes are used to implement specialized enum constants. Inner classes have access to instance variables of any lexically 词汇方面 enclosing instance; that is, the fields of the object an inner class is created in reference to. However, not all inner classes have enclosing instances; inner classes in static contexts, like an anonymous class used in a static initializer block, do not.
The Venn diagram below shows how these distinctions relate and combine; in particular, member-ness and inner-ness are not orthogonal properties.
(1)嵌套静态类是任何一个在另外一个类或者接口的代码体中声明的类,它作为外嵌类或者接口的静态成员。嵌套静态类的行为类似于顶级类,唯一的差别是嵌套静态类前除了有 Java 包的名字以外还有外嵌类的名字。嵌套静态类是静态成员,因此没有 this 指针指向外嵌类的实例,也就是说嵌套静态类不能访问外嵌类的实例数据。当一个重要的数据结构紧密的关联与外嵌类,并且该数据结构有足够的内容保证它能够拥有一个类的时候,一般情况下我们可以使用嵌套静态类。
内部类有三种形式:成员类、本地类和匿名类,每个类依次都是对它前一个类的改进。
(2)内部类的可视范围是它的直接外嵌类(这一点和嵌套静态类不同,嵌套类在其外嵌类之外也是可视的),也就是说内部类可以直接引用外嵌类中的任何成员。因为内部类与外嵌类的实例相关,所以内部类拥有两个 this 指针,一个指向内部类的实例本身,一个指向外嵌类实例。内部类的一个主要用途是用于 GUI 的事件处理程序。
(3)本地类是在代码块中声明的,因此它不是外嵌类的成员。一般来说,本地类在方法中进行声明。成员类和本地类的差别很小,通过把本地类移到方法的外部,我们可以很容易得把它转换成为成员类。它们两个之间最重要的差别是,本地类只能访问 final 的变量或者参数。
(4)匿名类允许我们把类的定义和实例的分配组合在一起。无须象其它任何嵌套类那样进行声明,我们可以直接用 new SomeClass() 实例化对象,并且在实例化的位置把整个类的实现都放在花括号中。
参考:
(1)深入理解为什么Java中方法内定义的内部类可以访问方法中的局部变量
(2)
Javac内部类本地类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。