多态及重写案例演示

利用封装,继承,多态知识点汇集来解决Teatcher和Student不同行为的案例演示,代码如下:

      /**
 * 人类
 * @author Administrator
 *
 */
public  abstract class People {
private  String name;
   private int age;
     public  abstract void eat() ;
     public void study() {
  System.out.println("学习了..");
  }

}

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

public class Student extends People {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("正在吃鸡");
}
public void study() {
System.out.println("正在学习大数据...");
}
/**
* 旅游
*/
public void travel() {
System.out.println("去叙利亚一日游...");
}

}

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

public class Teacher extends People {
@Override
public void eat() {
System.out.println("正在吃大龙呀");
}
public void study() {
System.out.println("正在学习人工智能...");
}
public void play() {
System.out.println("陪宝宝在玩耍");
}

}

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

public class Test {
public static void main(String[] args) {
//父类引用  变量名=new  具体的子类();
//点看左 输出看右
//创建一个数组 保存 2个人类的对象
  People  tt=new Teacher();   
      People  ss=new Student();   
      People[] peoples=new People[2];
       peoples[0]=ss;
       peoples[1]=tt;  
       //循环来查看数组中2个对象的 属性和方法
       for (People people : peoples) {
people.eat();
//people.travel();  学生所特有的
//需要再输出 学生和老师的不同的方法
if ( people  instanceof Student) {
Student  student= (Student) people;
student.travel();
}  
if (people instanceof Teacher) {
   Teacher teacher=(Teacher) people;
   teacher.play();
}  

       System.out.println("程序结束");

}

}

阅读更多

没有更多推荐了,返回首页