Core Java实例-接口抽象

来源:互联网 发布:淘宝服装店铺logo 编辑:程序博客网 时间:2024/05/17 06:41

 

接口的使用:

 

1 多态的情况下使用接口:分为编译时和运行时的状态。

2 注意对象的相同性。

3 强制转换的情况。

 

 

  1. package com;
  2. public interface Animal {
  3. }

 

  1. package com;
  2. /***
  3.  * 
  4.  * 鸟类
  5.  * 
  6.  * @author Administrator
  7.  *
  8.  */
  9. public class Bird implements Animal {
  10.     public Bird() {
  11.     
  12.     }
  13.     public String color;
  14.     private int age;
  15.     public int getAge() {
  16.         return age;
  17.     }
  18.     public void setAge(int age) {
  19.         this.age = age;
  20.     }
  21.     public String getColor() {
  22.         return color;
  23.     }
  24.     public void setColor(String color) {
  25.         this.color = color;
  26.     }
  27.     
  28.     
  29. }

 

  1. package com;
  2. public class SamllBird extends Bird {
  3. }

 

 

  1. package com;
  2. import java.lang.reflect.InvocationTargetException;
  3. public class Test {
  4.     public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
  5.         
  6.         Animal b = new Bird();
  7.         b.toString();
  8.         
  9.         Bird bird = (Bird)b;
  10.         bird.setColor("red");
  11.         
  12.         System.out.println(bird.getColor());
  13.         
  14.         System.out.println(b==bird);
  15.         
  16.         Animal sb = new SamllBird();
  17.         Bird bb = (Bird)sb;
  18.         System.out.println(sb==bb);
  19.         
  20.         System.out.println(b instanceof Animal);
  21.         System.out.println(bird instanceof Animal);
  22.         System.out.println(sb instanceof Animal);
  23.         
  24.         
  25.         
  26.         
  27.     }
  28. }

运行结果:

red
true
true
true
true
true

原创粉丝点击