多态

1.

abstract class Car
{
	String name;
	String color;
	public Car(){}
	public Car(String name, String color)
	{
		this.name = name;
		this.color = color;
	}
	public abstract void run();
}

class Bmw extends Car
{
	public Bmw()
	{
		super();
	}
	public Bmw(String name, String color)
	{
		super(name,color);
	}
	public void run()
	{
		System.out.println(this.name+"快速地跑了起来..."+this.color );
	}
}

class Bsj extends Car
{
	public Bsj()
	{
		super();
	}
	public Bsj(String name, String color)
	{
		super(name,color);
	}
	public void run()
	{
		System.out.println(this.name+"慢慢地跑了起来..."+this.color );
	}
}

class CarFactory
{
	String name;
//	Car bmw = new Bmw();
//	Car bsj = new Bsj();
	public CarFactory(String name)
	{
		this.name = name;
	}
//	public Car produce()
//	{
//		int a = (int)Math.round(Math.random()*1);
//		if(a == 0)
//			return bmw;
//		else 
//			return bsj;
//	}

	public Car produce()
	{
		int a = (int)Math.round(Math.random()*1);
		if(a == 0)
			return new Bmw("宝马","黑色");
		else
			return new Bsj("保时捷","白色");
	}
}

public class duotaiPractice
{
	public static void main(String[] args)
	{
		int x = 0;
		CarFactory cf = new CarFactory("红太阳制造车厂");
		while(x<5)
		{
			Car c = cf.produce();
			c.run();
			x++;
		}
	}
}

宝马快速地跑了起来...黑色
保时捷慢慢地跑了起来...白色
宝马快速地跑了起来...黑色
保时捷慢慢地跑了起来...白色
保时捷慢慢地跑了起来...白色
 

 

 

2. 接口关系下的多态

interface Dao
{
	public abstract void add();
	public abstract void delete();
}
class UserDao implements Dao
{
	public  void add()
	{
		System.out.println("增");
	}
	public  void delete()
	{
		System.out.println("删");
	}
}
public class InterfaceDuotai 
{
	public static void main(String[] args) 
	{
		Dao d = new UserDao();
		d.add();
		d.delete();
	}
}

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值