多态

来源:互联网 发布:微小企业会计软件好吗? 编辑:程序博客网 时间:2024/05/01 18:37

/*
多态:事物存在的多种体现形态。
人:男人,女人
动物:猫,狗
猫 x=new 猫();
动物 x=new 猫();//对象的多态
1.多态的体现
  父类的引用指向了自己的子类对象;Animal c=new Cat();
2.多态的前提
 类与类之间有关系;存在覆盖

3.多态的好处
  提高程序的扩张性
4.多态的弊端
  只能使用父类的引用访问父类的成员
4.多态的应用
*/
/*
动物;
猫 狗
*/
abstract class Animal
{
 abstract void eat();
}
class Cat extends Animal
{
 void catchMouse()
 {
  System.out.println("抓老鼠老鼠");
 }
 void eat()
 {
  System.out.println("吃老鼠");
 }
}
class Dog extends Animal
{
 void eat()
 {
  System.out.println("吃骨头");
 }
}
class Pig extends Animal
{
 void eat()
 {
  System.out.println("吃饲料");
 }
}
public class DuoTaiDemo
{
 public static void main(String[] args)
 {
  //Cat c=new Cat();
  //c.eat();
  //function(new Cat());
  //function(new Dog());
  //function(new Pig());
  Animal a=new Cat();//类型提升,向上转型
  a.eat();
  //如果想要调用猫的特有方法,怎么做?
  //强制将父类的引用,转成子类类型,向下转型
  Cat c=(Cat)a;
  c.catchMouse();

 }
 static void function(Animal a)//
 {
  a.eat();
 }
}


 

0 0
原创粉丝点击