多态的使用

public class DuoTai{
public static void main(String args[]){
//多态最经典的两句:
// 1, 子类实例 是 父类对象 <==Person p = new Student("Jack",30,"Game");
// 2, 运行时多态---new谁调谁 <=== p.toString()---先调子类Student中的该方法,若没有,再调父类Person中的该方法,若还没有则继续往更上层的父类去找

Person p1 = new Person("张三",25);
Person p2 = new Person("李四",22);
Person p3 = new Student("Jack",30,"Game");
Person p4 = new Student("Rose",22,"singing");
Student s1 = new Student("小李",23,"software");
Student s2 = new Student("飞标",26,"P.E.");

Person p = s1;
System.out.println("p:"+p);

Person ps[] ={ p1, p2, p3,p4, s1,s2 };
//System.out.println(ps);
print(ps);
System.out.println("-------1-------");
print2(ps);
System.out.println("-------2-------");

// Object objs1[] = { p1, p2, p3,p4, s1,s2 };
// print(objs1);//不行,编译时类型不一致:需要Person但这里声明的是Object

Object objs[] = {p1, p2, p3,new MyDate(2008,8,8), p4, s1,s2, new MyDate(2016,4,10) };
print2(objs);

}

public static void print( Person ps[] ){
for(int i=0;i<ps.length;i++){
System.out.println( ps[i].toString() );//多态:new谁调谁
}
}

public static void print2( Object objs[] ){
for(Object obj: objs){
System.out.println( obj.toString() );//多态:new谁调谁
}
}

}

---------------------------------------

public class Demo{
public static void main(String args[]){

//demo1();
demo2();

}
public static void demo2(){
Person p1 = new Person("张三",25);
Person p2 = new Person("李四",22);
int x = p2.oldThan( p1 );
System.out.println("x="+ x);

Student s = new Student("Jack",30,"Game");
int y1 = s.oldThan(p1);
System.out.println("y1="+ y1);
int y2 = p1.oldThan( s );
System.out.println("y2="+ y2);
Student s2 = new Student("小李",23,"software");
int y3 = s.oldThan( s2 );
System.out.println("y3="+ y3);

Person p = new Student("飞标",26,"P.E.");
int y4 = s.oldThan( p );
System.out.println("y4="+ y4);

}

public static void demo1(){
Student s1 = new Student("张三",25,"Computer");
s1.talkSpec();//调Student类中的方法,以学生的形态来呈现
s1.talk();//调Person类中的方法,以Persn的形态来呈现
System.out.println(s1.count);

s1.set("Jack",30);
System.out.println(s1);
s1.set("Rose",23,"Singing");
System.out.println(s1);
System.out.println("------------");

//类型多态
Student s2 = new Student("小李",23,"software");
boolean b1 = s2 instanceof Student; //s2是Student类型
System.out.println("b1:"+b1);//true
boolean b2 = s2 instanceof Person;//s2是Person类型
System.out.println("b2:"+b2);//true

//※※最经典的多态----子类的实例是父类对象
Person p = new Student("飞刀",25,"software");
System.out.println("p:"+p.toString());
//延伸
Object obj = new Student("飞标",26,"P.E.");
System.out.println("obj:"+obj.toString());//new谁调谁

Person p2 = new Person("五王",23);
System.out.println( p2 instanceof Person );//true
System.out.println( p2 instanceof Student );//false ---父类实例不是子类对象
//Student ps = new Person("孙二",30);//ERROR:原因见上一句
//System.out.println( ps );
}
}

posted @ 2016-06-20 17:20  折腾青春  阅读(182)  评论(0编辑  收藏  举报