内部类 static内部类

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();
}
}
class Test {
public static void main(String[] args) {
Parcel3 p = new Parcel3();
Contents c = p.cont();
Destination d = p.dest("Tanzania");
// Illegal -- can't access private class:
//! Parcel3.PContents c = p.new PContents();
}
}

我们准备实现某种形式的接口,使自己能创建和返回一个句柄。内部类的对象默认持有创建它的那个封装类的一个对象的句柄。若想在除外部类非static 方法内部之外的任何地方生成内部类的一个对象,必须将那个对象的类型设为“外部类名.内部类名”( Parcel3.PContents c = p.new PContents();),就象 main()中展示的那样。

 要解决一个复杂的问题,并希望创建一个类,用来辅助自己的程序方案。同时不愿意把它公开。普通(非内部)类不可设为private或 protected——只允许 public或者“友好的”。

 static内部类

(1) 为创建一个 static内部类的对象,我们不需要一个外部类对象。

private static class PContents
extends Contents {
private int i = 11;
public int value() { return i; }
}

public static Contents cont() {
return new PContents();
}

Contents c = cont();
(2) 不能从 static内部类的一个对象中访问一个外部类对象
但在存在一些限制:由于static 成员只能位于一个类的外部级别,所以内部类不可拥有static 数据或
static内部类。
倘若为了创建内部类的对象而不需要创建外部类的一个对象,那么可将所有东西都设为static。为了能正常
工作,同时也必须将内部类设为static。static内部类可以成为接口的一部分。

interface IInterface {
static class Inner {
int i, j, k;
public Inner() {}
void f() {}
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值