内部类——this和new及向上转型
2018-02-03 00:00
267 查看
一、.this
package com.lh.innerclass.class2; public class DotThis { public void f(){ System.out.println("DotThis.f()"); } class Inner{ public DotThis outer(){ //调用当前外部类对象 return DotThis.this; } } public Inner inner(){ return new Inner(); } public static void main(String[] args) { DotThis dotThis = new DotThis(); DotThis.Inner inner = dotThis.inner(); inner.outer().f(); System.out.println(dotThis == inner.outer()); } }
二、.new
package com.lh.innerclass.class2; public class DotNew { class Inner{} public static void main(String[] args) { DotNew dotNew = new DotNew(); //创建内部类实例对象 DotNew.Inner inner = dotNew.new Inner(); } }
三、内部类与向上转型
package com.lh.innerclass.class2.upward; /*** * * * 内部类与向上转型(基类或接口,隐藏内部实现细节) * * @author Liu * */ public class Parcel { //定义为私有,外部无法访问 private class PContents implements Contents{ private int i = 11; public int value(){ return this.i; } } //定义为受保护的,外部访问收到限制 protected class PDestination implements Destination{ private String label; //构造方法私有,外部不能直接new private PDestination(String whereTo){ this.label = whereTo; } public String readLabel(){ return this.label; } } //提供公共方法,用于返回接口类型内部实现 public Contents contents(){ return new PContents(); } //提供公共方法,用于返回接口类型内部实现 public Destination destination(String dest){ return new PDestination(dest); } //程序入口 public static void main(String[] args) { Parcel parcel = new Parcel(); Contents contents = parcel.contents(); Destination destination = parcel.destination("Singapore"); System.out.println(contents.value()); System.out.println(destination.readLabel()); } }
相关文章推荐
- java炒冷饭系列10 内部类 使用.this与.new和向上转型
- 关于父类引用指向子类对象(A a = New B();)的使用,理解向上转型
- 内部类与向上转型
- 内部类与向上转型
- 内部类与向上转型
- 内部类之.this&&.new
- 内部类向上转型为接口
- 【java】内部类向上转型为接口例子
- 从头认识java-8.3 内部类的.this和.new语法
- 从头认识java-8.4 内部类与向上转型
- 内部类与向上转型
- 内部类向上转型为接口
- 10.4 内部类与向上转型
- Java之内部类与向上转型详解(附源码)
- java中向上转型时变量类型由声明时决定还是由new决定的理解
- 内部类向上转型为接口
- Java向上转型和向下转型(附详细例子)
- 当我new class的时候,提示以下错误: Unable to parse template "Class" Error message: This template did not produce
- 向上转型--Upcasting
- 匿名内部类new 父类或者接口(){定义子类的内容(如函数等)}