您的位置:首页 > 编程语言 > Java开发

Java之内部类的初级应用详解(附源码)

2016-07-23 10:29 531 查看

示例源码

在本节中我们将讲述内部类应用中的一个更典型的情况:外部类将有一个方法,该方法返回一个指向内部类的引用,就像在to()contents()方法中看到的那样。

package com.mufeng.thetenthchapter;

public class Parcell2 {

class Contents {
private int i = 11;

public int value() {
return i;
}
}

class Destination {
private String label;

public Destination(String whereTo) {
// TODO Auto-generated constructor stub\
label = whereTo;
}

String readLabel() {
return label;
}
}

public Destination to(String s) {
return new Destination(s);
}

public Contents contents() {
return new Contents();
}

public void ship(String dest) {
Contents c = contents();
Destination d = to(dest);
System.out.println(c.value());
System.out.println(d.readLabel());
}

public static void main(String[] args) {
Parcell2 p = new Parcell2();
p.ship("Tasmania");

System.out.println("--------我是分割线----------");

Parcell2 q = new Parcell2();
Parcell2.Contents c = q.contents();// (或者 q.new Contents())

Parcell2.Destination d = q.to("Borneo");// (或者 q.new
// Destination("Borneo"))

System.out.println(c.value());
System.out.println(d.readLabel());
}

}


输出结果

11
Tasmania
--------我是分割线----------
11
Borneo


源码解析

如果想从外部类的非静态方法之外的任意位置创建某个内部类的对象,那么必须像在main()方法中那样,具体地指明这个对象的类型:OuterClassName.InnerClassName
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: