Core Java執行個體-介面抽象

來源:互聯網
上載者:User

 

介面的使用:

 

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.