隐藏细节
例子:
abstract class Contents {
abstract public int value();
}
interface Destination {
String readLabel();
}
public class Parcel3 {
private class PContents extends Contents {
private int i = 11;
public int value() { return i; }
}
protected class PDestination implements Destination {
private String label;
private PDestination(String whereTo) {
label = whereTo;
}
public String readLabel() { return label; }
}
public Destination dest(String s) {
return new PDestination(s);
}
public Contents cont() {
return new PContents();
}
}
内部类PContents 被设为private,所以除了Parcel3 之外,其他任
何东西都不能访问它。PDestination 被设为protected,所以除了Parcel3,Parcel3 包内的类(因为
protected 也为包赋予了访问权;也就是说,protected 也是“友好的”),以及Parcel3 的继承者之外,其
他任何东西都不能访问PDestination。这意味着客户程序员对这些成员的认识与访问将会受到限制。匿名内部类(anonymous inner class)
例子:
package com.trueteng.test;
public class Parcel6 {
public Contents cont() {
return new Contents() {
private int i = 11;
public int value() {
return i;
}
}; // 分号这里必须要
}
//下面的内部类定义方法如同上面的匿名内部类
public Contents cont1(){
class MyContents implements Contents{
private int i = 11;
public int value(){
return i;
}
}
return new MyContents();
}
public static void main(String[] args) {
Parcel6 p = new Parcel6();
Contents c = p.cont();
Contents c1 = p.cont1();
}
}