<a href="http://www.verejava.com/?id=16992857876159">http://www.verejava.com/?id=16992857876159</a>
1/** 2 知识点: 内部类 3 1. 内部类的定义 4 2. 内部类的优缺点 5 3. 外部类怎么实例化其他类的内部类 6 4. 方法中定义内部类 7 如果在方法中定义内部类,方法中的内部类要访问变量, 需要加final 关键字 8 5. static 声明内部类 9 10 题目:母亲怀了孕, 母亲的营养决定孩子的健康成长 11 思路: 12 1. 抽象出类 : 母亲(Mother), 孩子(Baby) 13 2. 找出类的关系: 孩子在母亲里面 Baby in Mother 14 3. 抽象出方法: 母亲吃东西 (eat) 15*/ 16public class InnerClass2 17{ 18 public static void main(String[] args) 19 { 20 //实例化母亲 21 Mother mother=new Mother("lucy"); 22 //母亲吃苹果 23 mother.eat("苹果"); 24 25 } 26} 27class Mother 28{ 29 private String name; 30 private String food;//母亲吃的食物 31 32 public Mother(String name) 33 { 34 this.name=name; 35 } 36 37 public String getName() 38 { 39 return this.name; 40 } 41 public void setName(String name) 42 { 43 this.name=name; 44 } 45 46 /** 47 母亲吃东西 48 */ 49 public void eat(final String food) 50 { 51 this.food=food; 52 System.out.println(this.name+" 吃了 "+this.food); 53 class Baby 54 { 55 /** 56 孩子从母亲吃的东西中吸收营养 57 */ 58 public void eat() 59 { 60 System.out.println("孩子从母亲吃的 "+food+" 中吸收营养"); 61 } 62 } 63 //母亲吃东西的同时 孩子也吃东西 64 new Baby().eat(); 65 } 66 67 68} 69
<a href="http://www.verejava.com/?id=16992857876159">http://www.verejava.com/?id=16992857876159</a>