Java 面向对象 之 多态实例1
http://www.verejava.com/?id=16992843565554
/**
题目: 孩子吃(苹果,葡萄,芒果)
思路:
1. 抽象出类 : 孩子(Baby), 苹果(Apple),葡萄(Grape)
2. 找出类的关系: 苹果,葡萄 -> 孩子
3. 找出属性: 孩子(姓名,苹果引用,葡萄引用) 苹果(名称) 葡萄(名称)
4. 找出方法: 孩子吃(eat)苹果或者葡萄
*/
public class Polymorphism2
{
public static void main(String[] args)
{
//实例化一个Baby
Baby baby=new Baby("李明");
//实例化一个苹果 和 一个葡萄
Apple apple=new Apple("红富士");
Grape grape=new Grape("黑葡萄");
Mango mango=new Mango("大芒果");
//李明吃苹果和葡萄
baby.eat(apple);
System.out.println(baby.getName()+" 高兴的说我吃了 "+baby.getApple().getName());
baby.eat(grape);
System.out.println(baby.getName()+" 高兴的说我吃了 "+baby.getGrape().getName());
baby.eat(mango);
System.out.println(baby.getName()+" 高兴的说我吃了 "+baby.getMango().getName());
}
}
class Baby
{
private Apple apple;
private Grape grape;
private Mango mango;
private String name;
public Baby(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
public Apple getApple()
{
return this.apple;
}
public Grape getGrape()
{
return this.grape;
}
public Mango getMango()
{
return this.mango;
}
/**
吃苹果
*/
public void eat(Apple apple)
{
this.apple=apple;
}
/**
吃葡萄
*/
public void eat(Grape grape)
{
this.grape=grape;
}
/**
吃芒果
*/
public void eat(Mango mango)
{
this.mango=mango;
}
}
class Apple
{
private String name;
public Apple(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
}
class Grape
{
private String name;
public Grape(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
}
class Mango
{
private String name;
public Mango(String name)
{
this.name=name;
}
public String getName()
{
return this.name;
}
}