public class 多态 {
private 多态[] qtest = new 多态[6];
private int nextIndex = 0;
public void draw(多态 q){
if (nextIndex<qtest.length){
qtest[nextIndex] = q;
System.out.println(nextIndex);
nextIndex++;
}
}
public static void main(String[] args) {
多态 q = new 多态();
q.draw(new Square());
q.draw(new Paral());
q.draw(new Changfang());
}
}
class Square extends 多态{ //nextIndex=0
public Square(){
System.out.println("正方形");
}
}
class Paral extends 多态{ //nextIndex=1
public Paral(){
System.out.println("平行四边形");
}
}
class Changfang extends 多态{ //nextIndex=2
public Changfang(){
System.out.println("长方形");
}
}
接口是一类对象的抽象,比如交通工具,不论是汽车还是飞机都是交通工具,他们可以有一个共同的方法
interface Vehicle{
void run();
}
//那么所有的实现了vehicle这个接口的类必须重写接口内的方法
//汽车
class Car implements vehicle{
@Override
public void run(){
System.out.println("汽车行驶中......");
}
}
//飞机
class Plane implements vehicle{
@Override
public void run(){
System.out.println("飞机飞行中......");
}
}
public static void main(String args[]){
//父类引用指向子类对象
Vehicle vehicle = new Car();
//此时执行car类的run方法,输出 汽车行驶中。。。。
vehicle.run();
vehicle = new Plane();
//此时执行plane类的run方法,输出 飞机飞行中。。。。。。
vehicle.run();
//虽然调用的都是vehicle这个接口的run方法,但是由于指向的对象不同(而对象都实现了这个接口并且重写了其中的run方法,所以输出的结果是不一样的,这就是多态。
//多态并不只是通过接口才可以实现,父类也可以、实际上接口也是类,只不过是一个所有方法都是抽象方法的类,是一个完完全全的抽象类。
//多态的三个必要条件
//1:继承(extends,implements)
//2:重写 Override
//3:父类引用指向子类对象,就像上面例子中定义了一个vehicle对象,实际new 的是Car或者Plane
//这样调用父类引用被重写的方法时就会有多态存在
}