java嵌套类、静态嵌套类、内部类

官网文档:[url=http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html]Nested Classes[/url]

[b]什么是嵌套类及内部类?[/b]
可以在[color=red]一个类的内部定义另一个类,这种类称为嵌套类(nested classes)[/color],它有两种类型:静态嵌套类和非静态嵌套类。[color=red]非静态嵌套类,也被称作为内部类(inner class)[/color]。嵌套类是其外部类的成员,可以被声明为private, public, protected, 或者package private。 (此时,外部类只能被声明为public 或者package private。)
嵌套类 从JDK1.1开始引入。其中内部类(inner类)又可分为三种:
[list]
[*]在一个类(外部类)中直接定义的内部类;
[*]在一个方法(外部类的方法)中定义的内部类;
[*]匿名内部类。
[/list]

class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}

[b]为什么使用嵌套类(什么时候使用嵌套类):[/b]
[list]
[*]It is a way of [b]logically grouping classes[/b] that are only used in one place. - If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
[*]如果[color=red]一个类只在一个地方被使用,同时这个类和另外一个类在逻辑上紧密相关[/color],那么这个类可以被设计成内部类。
[*]It increases [b]encapsulation[/b]. - Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
[*]增强了封装性
[*]Nested classes can lead to [b]more readable and maintainable[/b] code. - Nesting small classes within top-level classes places the code closer to where it is used.
[*]嵌套类增加代码的[color=red]可读性和可维护性[/color](因为嵌套类从逻辑上来说都是相关的)。
[/list]
[b]静态嵌套类的(static nested class):[/b]
[list]
[*]可以独立于外部类被实例化
[*]无法访问外部类中的非静态变量和方法
[*]静态嵌套类要和其外部类的实例变量(或者其他类)交互的话,[color=red]其行为和一般顶级类一样[/color]
[*]实际上,[color=red]静态嵌套类就是[/color]一个为了打包方便而被嵌套进外部类的[color=red]顶级类[/color]。
[/list]
[b]非静态嵌套类(内部类inner class):[/b]
[list]
[*]想要实例化必须先实例化外部类。
[*]可以访问外部类中的需要实例化的变量和方法,
[/list]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值