6、继承的应用示例
实现一个化妆品商城中的化妆品管理
1、定义一个化妆品类(Cosmetic)
2、定义一个化妆品管理类(CosmeticMenager)
(1)实现进货功能
(2)可以输出所有化妆品信息功能
3、使用继承实现一个可按单价排序输出所有化妆品的功能
4、使用继承实现一个只输出进口化妆品的功能
import java.util.Arrays;
public class Demo1
{
public static void main(String[] args)
{
CosmaticManager cm = new CosmaticManager();
//添加
cm.add(new Cosmatic("香奈儿", "进口", 1000));
cm.add(new Cosmatic("韩束", "国产", 298));
cm.add(new Cosmatic("一叶子", "国产", 399));
cm.add(new Cosmatic("美联臣", "进口", 888));//这里多添加了一个
//看看cm里的下标是不是还是3(这里应该是3*3/2+1=5)
/*System.out.println(cm.length);*/
//再输出上面的产品
cm.printInfo();
}
}
//化妆品类
class Cosmatic
{
private String name; //名字
private String type; //进口国产
private int prise; //价格,忽略小数位
public Cosmatic(){}
public Cosmatic(String name, String type, int prise)
{
this.name = name;
this.type = type;
this.prise = prise;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setType(String type)
{
this.type = type;
}
public String getType()
{
return type;
}
public void getPrise(int prise)
{
this.prise = prise;
}
public int getPrise()
{
return prise;
}
public String getInfo()
{
return "name = "+name+" type = "+type+" prise = "+prise; //返回信息
}
}
//化妆品管理类
class CosmaticManager
{
protected Cosmatic[] cs = new Cosmatic[3]; //自定义一个Cosmatic数组,默认数组有3个空
protected int count = 0; //这是数组的一个下标,记住,count所指向的下标为空,所以后面i或j是不能小于等于count的
public void add(Cosmatic c) //添加一个化妆品
{
int size = cs.length;
if(count >= size)
{
int newLen = size * 3 / 2 + 1;
cs = Arrays.copyOf(cs, newLen);
}
cs[count] = c;
count++;
}
public void printInfo() //输出所有产品
{
for(int i = 0; i < count; i++)
{
System.out.println(cs[i].getInfo());
}
}
}
//继承:从小到大排列商品(冒泡)
class SortCosmaticManager extends CosmaticManager
{
public void printInfo()
{
Cosmatic[] temp = Arrays.copyOf(cs, count);
for(int i = 0; i < temp.length-1; i++)
{
for(int j = 0; j < temp.length-i-1; j++)
{
if(temp[j].getPrise() > temp[j+1].getPrise())
{
Cosmatic c = temp[j];
temp[j] = temp[j+1];
temp[j+1] = c;
}
}
}
for(Cosmatic c: temp) //记住这个for是在printInfo()里面的
{
System.out.println(c.getInfo());
}
}
}
//继承:只输出进口化妆品的功能
class ImportCosmeticManager extends CosmaticManager
{
public void printInfo()
{
for(int i = 0; i < count; i++)
{
//这里字符串比较不能用==,要用字符串里的"".equals()
if("进口".equals(cs[i].getType())) //这边说的是:“进口”等于cs[i].getType()吗,要是等于,就输出这个化妆品
{
System.out.println(cs[i].getInfo());
}
}
}
}
结果不演示了,大家可以改一下主函数的CosmeticManager cm = new CosmeticManager();为SortCosmaticManager cm = new SortCosmaticManager();或ImportCosmeticManager cm = new ImportCosmeticManager ();试一试