java接口与多态

接口无法被实例化,但是可以被实现。在 Java 中,接口类型可用来声明一个变量,他们可以成为一个空指针,或是被绑定在一个此接口实现类的对象。

接口可以用来作为一种引用类型使用,在创建对象时使用接口名,也就是用接口类型的变量指向接口实现类的实例。得到这个引用后,可以访问接口中定义的方法。
例:

public class Test {
    public static void main(String[] args) {
      show(new Cat());  // 以 Cat 对象调用 show 方法
      show(new Dog());  // 以 Dog 对象调用 show 方法

      Animal a = new Cat();  // 向上转型,Cat类型转成Animal类型
      a.eat();               // 调用的是 Cat 的 eat
      Cat c = (Cat)a;        // 向下转型  
      c.work();        // 调用的是 Cat 的 work
  }  

    public static void show(Animal a)  {
         a.eat();  
        // 类型判断
        if (a instanceof Cat)  {  // 猫做的事情 
            Cat c = (Cat)a;  
            c.work();  
        } else if (a instanceof Dog) { // 狗做的事情 
            Dog c = (Dog)a;  
            c.work();  
        }  
    }  
}

Interface  Animal {  
    public void eat();  
}  

class Cat implements Animal {  
    public void eat() {  
        System.out.println("吃鱼");  
    }  
    public void work() {  
        System.out.println("抓老鼠");  
    }  
}  

class Dog implements Animal {  
    public void eat() {  
        System.out.println("吃骨头");  
    }  
    public void work() {  
        System.out.println("看家");  
    }  
}

猜你喜欢

转载自blog.csdn.net/yan3013216087/article/details/78819770