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。相关文章推荐
- java中的值传递和引用传递问题
- 深入理解java虚拟机(一):java内存区域(内存结构划分)
- Spring boot 整合CXF开发webService
- Java 中的 static 使用之静态方法
- JavaSE学习笔记之-----异常处理
- Struts2支持的结果类型
- Spring入门篇学习笔记(3)
- 疯狂java的基本总结
- protobuf安装配置和编译成java文件教程(for mac)
- Struts2框架运行机制
- Java集合排序总结
- Spring事务管理--(一)数据库事务隔离级别与mysql引擎基础讲解
- 反转部分单向链表
- JavaSE基础(五)
- javaWeb项目中,SSM配置,使用namespace的话,JSP页面跳转的找不到指定的action
- Spring Cache 介绍
- Java之内部类语法详解(附源码)
- spring+mybatis 多数据源切换
- 获取SpringMVC上下文bean实例-SpringContextUtil
- Java中的Iterator(迭代器)的一般用法