一、定义
在一个类内部的类称为内部类。
二、作用
信息隐藏、实现多继承。
三、例子
1 package iijesus.java.basic; 2 3 /** 4 * 内部类的结构、用法实例 5 * 业务需求:让投资者Investor继承赌徒Gambler和工人Worker的买卖方法,同时实现庄家Banker的买卖方法,达到多继承的目的。 6 * 注意:Gambler、Worker和Banker的买卖方法名是一样的,避免调用混乱。 7 */ 8 9 //庄家接口,有买、卖方法 10 interface Banker 11 { 12 public void buy(); 13 public void sell(); 14 } 15 16 //赌徒类,有买、卖方法 17 class Gambler 18 { 19 void buy() 20 { 21 System.out.println("gambler buying..."); 22 } 23 void sell() 24 { 25 System.out.println("gambler selling..."); 26 } 27 } 28 29 //工人类,有买、卖方法 30 class Worker 31 { 32 void buy() 33 { 34 System.out.println("worker buying..."); 35 } 36 void sell() 37 { 38 System.out.println("worker selling..."); 39 } 40 } 41 //投资者类,有买、卖方法 42 public class Investor 43 { 44 //投资者继承赌徒的买卖方法 45 private class GamblerSon extends Gambler 46 { 47 void buy() 48 { 49 super.buy(); 50 } 51 void sell() 52 { 53 super.sell(); 54 } 55 } 56 //投资者继承工人的买卖方法 57 private class WorkerSon extends Worker 58 { 59 void buy() 60 { 61 super.buy(); 62 } 63 void sell() 64 { 65 super.sell(); 66 } 67 } 68 //投资者实现庄家的买卖方法 69 private class BankerSon implements Banker 70 { 71 public void buy() 72 { 73 System.out.println("banker buying..."); 74 } 75 public void sell() 76 { 77 System.out.println("banker selling..."); 78 } 79 } 80 //投资者的买方法 81 public void buy(String type) 82 { 83 if(type.equals("gambler")) 84 { 85 new GamblerSon().buy(); 86 } 87 else if(type.equals("banker")) 88 { 89 new BankerSon().buy(); 90 } 91 else if(type.equals("worker")) 92 { 93 new WorkerSon().buy(); 94 } 95 } 96 //投资者的卖方法 97 public void sell(String type) 98 { 99 if(type.equals("gambler")) 100 { 101 new GamblerSon().sell(); 102 } 103 else if(type.equals("banker")) 104 { 105 new BankerSon().sell(); 106 } 107 else if(type.equals("worker")) 108 { 109 new WorkerSon().sell(); 110 } 111 } 112 //调用各个继承者的买卖方法 113 public static void main(String[] args) 114 { 115 Investor investor = new Investor(); 116 investor.buy("worker"); 117 investor.buy("gambler"); 118 investor.buy("banker"); 119 120 investor.sell("worker"); 121 investor.sell("gambler"); 122 investor.sell("banker"); 123 124 } 125 }