我的理解是,通过同一标识符对不同的方法,变量,对象进行调用。提高代码利用性,有利程序扩展。以下是一个简单的示范:
- /**
- 以下是一段简单的多态演示代码。
- */
- abstract class Car
- {
- String ID;
- String colour;
- Car(){}
- abstract void run();
- }
- class Truck extends Car
- {
- Truck(String ID,String colour)
- {
- this.ID = ID;
- this.colour = colour;
- }
- void run() //复写run方法,打印车牌和颜色;
- {
- System.out.println("ID: "+ID+" colour: "+colour);
- }
- }
- class Roadster extends Car
- {
- int speed;
- Roadster(String ID,String colour,int speed)
- {
- this.ID = ID; //局部变更隐藏了类变量,使用this关键字调出类变量;
- this.colour = colour;
- this.speed = speed;
- }
- Roadster(int speed,String ID,String colour) //参数顺序不同,覆写构造方法;
- {
- this.ID = ID;
- this.colour = colour;
- this.speed = speed;
- }
- void run()
- {
- //此处除了车牌和颜色,还加入了对时速的打印输出;
- System.out.println("ID: "+ID+" colour: "+colour+" speed : "+speed+" kilometres per hour");
- }
- }
- public class CarDemo
- {
- public static void main(String[] args)
- {
- Car c[] = new Car[3];
- //父类的引用指向子类的对象;
- c[0] = new Truck("FY-999","blue");
- c[1] = new Roadster(210,"BJ-001","white");
- c[2] = new Roadster("GY-888","red",200);
- for(Car car :c)
- {
- car.run(); //不同的子类对象可以用foreach循环一起调用;
- }
- }
- }
复制代码
运行效果:
|