Java 面向对象 之 内部类

http://www.verejava.com/?id=16992853945358

/**
    知识点: 内部类
        1. 内部类的定义
        2. 内部类的优缺点
        3. 外部类怎么实例化其他类的内部类
        4. 方法中定义内部类
        5. static 声明内部类

    题目:母亲怀了孕, 母亲的营养决定孩子的健康成长
    思路:
        1.  抽象出类 :  母亲(Mother), 孩子(Baby)
        2.  找出类的关系: 孩子在母亲里面 Baby in Mother
        3.  抽象出方法: 母亲吃东西 (eat)
*/
public class InnerClass
{
    public static void main(String[] args)
    {
        //实例化母亲
        Mother mother=new Mother("lucy");
        //母亲吃苹果
        mother.eat("苹果");

        //小孩子从苹果中吸取营养
        Mother.Baby baby=mother.new Baby();
        baby.eat();
    }
}
class Mother
{
    private String name;
    private String food;//母亲吃的食物

    public Mother(String name)
    {
        this.name=name;
    }

    public String getName()
    {
        return this.name;
    }
    public void setName(String name)
    {
        this.name=name;
    }

    /**
        母亲吃东西
    */
    public void eat(String food)
    {
        this.food=food;
        System.out.println(this.name+" 吃了 "+this.food);
    }

    class Baby
    {
        /**
            孩子从母亲吃的东西中吸收营养
        */
        public void eat()
        {
            System.out.println("孩子从母亲吃的 "+food+" 中吸收营养");
        }
    }
}

http://www.verejava.com/?id=16992853945358

猜你喜欢

转载自www.cnblogs.com/verejava/p/9207383.html
今日推荐