1 多态(ploymorphism)指一个程序中相同的名字表示不同的含义的情况
1.1 编译时多态:函数重载(overload),多个同名的不同方法
e.g. p.sayhallo() p.sayhallo("wang")
1.2 运行时多态
2 方法调用
注意:上溯造型(upcasting)----把派生类型当做基本类型处理
2.1 虚方法调用----可以实现运行时的多态
2.2 instanceOf
if(实例名 instanceOf 类型名)
public class DrawShape { public static void main(String[] arg){ Shape t = new Triangle(); Shape r = new Rectangle(); Shape q = new Quadrangle(); drawStuff(t); drawStuff(r); drawStuff(q); } static void drawStuff(Shape shape){ shape.draw(); } } class Shape{ public void draw(){ System.out.println("Draw a shape;"); }; } class Triangle extends Shape{ public void draw(){ System.out.println("Draw a triangle;"); } } class Rectangle extends Shape{ public void draw(){ System.out.println("Draw a Rectangle;"); } } class Quadrangle extends Shape{ public void draw(){ System.out.println("Draw a Quadrangle;"); } }
2.3 三种非虚方法调用
原文:http://www.cnblogs.com/penghuster/p/4840985.html