内部类
可以将一类类的定义放在另一个类的内部,这就是内部类。
10.1创建内部类
把类的定义置于外围类的里面
public class Parcel1{
class Contents {
private int i = 11;
public int value(){return i;}
}
//...
}
10.2链接到外部类
当生成一个内部类的对象时,此对象与制造它的外围对象之间就有了一种联系,所以它能访问其外围对象的所有成员,而不需要任何特殊条件。即内部类自动拥有对其外围类所有成员的访问权。
在内部类是非static类时,内部类的对象只能在与其外围类对象想关联的情况下才能被创建。
interface Selector{
void f();
}
public class Sequence{
int n = 5;
private class SequenceSelector implements Selector{
void f(){ n = 100;}
}
public Selector selector(){
return new SequenceSelector();
}
public static void main(String[] args){
Sequence seq = new Sequence();
Selector selector = seq.selector();
}
}
10.3使用.this与.new
.this:生成外部类对象的引用
示例:
public class Outer{
void f(){//...}
public class Inner{
public Outer getOuter(){
return Outer.this;
}
}
public Inner inner(){return new Inner();}
public static void main(String[] args){
Outer outer = new Outer();
outer.Inner inn = outer.inner();
inn.getOuter.f();
}
}
.new:创建某个内部类对象
示例:
public class DotNew{
public class Inner{}
public static void main(String[] args){
DotNew dn = new DotNew();
DotNew.Inner dni = dn.new Inner();
}
}
10.4内部类与向上转型
当将内部类向上转型为基类/接口的时候,内部类就有了用武之地。此内部类(某个接口的实现)能够完全不可见,并且不可用。所得到的只是指向基类或接口的引用,所以能够很方便地隐藏实现细节。
public interface Contents{
int value();
}
class Parcel4{
private class PContents implements Contents{//...}
public Contents contents{ return new PContents();}
}
public class TestParcel{
public static void main(String[] args){
Parcel4 p = new Parcel4();
Contents c = p.contents();
//! Parcle4.PContents pc = p.new PContents();
//can't access private class
}
}
private内部类给设计者提供了一种途径,通过这种方式可以完全组织任何依赖于类型的编码,并且完全隐藏了实现的细节。
10.5在方法和作用域内的内部类
Local classess/局部内部类
public class Parcel5{
public Destination destination(String s){
class PDestination implements Destination {
private String label;
private PDestination(String whereTo){
label = whereTo;
}
public String readLabel(){return label;}
}
return new PDestination();
}
public static void main(String[] args){
Parcel5 p = new Parcel5();
Destination d = p.destination();
}
}
10.6匿名内部类
没有名字的内部类
public class Parcel7{
public Contents contents(){
return new Contents(){
private int i = 11;
public int value(){return i;}
};
}
public static void main(String[] args){
Parcel7 p = new Parcel7();
Contents c = p.contents();
}
}
10.7嵌套类
static内部类
1、要创建嵌套类的对象,并不需要其外围类的对象;
2、不能从嵌套类的对象中访问非静态的外围类对象;
嵌套类还可以作为接口的一部分;
10.8为什么需要内部类
内部类提供了某种进入其外围类的窗口;
内部类允许继承多个非接口类型;
补充之前一篇文章小结
嵌套类