介面的使用:
1 多態的情況下使用介面:分為編譯時間和運行時的狀態。
2 注意對象的相同性。
3 強制轉換的情況。
- package com;
- public interface Animal {
- }
- package com;
- /***
- *
- * 鳥類
- *
- * @author Administrator
- *
- */
- public class Bird implements Animal {
- public Bird() {
-
- }
- public String color;
- private int age;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getColor() {
- return color;
- }
- public void setColor(String color) {
- this.color = color;
- }
-
-
- }
- package com;
- public class SamllBird extends Bird {
- }
- package com;
- import java.lang.reflect.InvocationTargetException;
- public class Test {
- public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
-
- Animal b = new Bird();
- b.toString();
-
- Bird bird = (Bird)b;
- bird.setColor("red");
-
- System.out.println(bird.getColor());
-
- System.out.println(b==bird);
-
- Animal sb = new SamllBird();
- Bird bb = (Bird)sb;
- System.out.println(sb==bb);
-
- System.out.println(b instanceof Animal);
- System.out.println(bird instanceof Animal);
- System.out.println(sb instanceof Animal);
-
-
-
-
- }
- }
運行結果: