最近看了一篇介绍接口和抽象类的文章,发现还不错。以下是对文章的总结和自己写的一个事例。总结的可能有些粗糙,建议直接看原文,文章地址:http://www.jiagoushuo.com/article/1000074.html#rd?sukey=ecafc0a7cc4a741b8d173e3714b0d37aed2569a28a62b5eb357b1573f19c80eef74baa1c870e39b9068f6b8bb5f6709c
package com.zxy.Test20160410; public abstract class Birds { private String type; private String color; private double weight; public Birds(String type, String color, double weight){ this.setType(type); this.setColor(color); this.setWeight(weight); } public abstract void eat(); public void print(){ System.out.println("种类:"+this.getType()); System.out.println("颜色:"+this.getColor()); System.out.println("重量:"+this.getWeight()); } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } }
package com.zxy.Test20160410; public interface Fly { void fly(); }
package com.zxy.Test20160410; public interface Run { void run(); }
package com.zxy.Test20160410; /** * 蜂鸟 * @author hsoft3 * */ public class HummingBird extends Birds implements Fly { public HummingBird(String type, String color, double weight){ super(type, color, weight); } @Override public void fly() { System.out.println("我是"+this.getType()+",我会fly。"); } @Override public void eat() { System.out.print("我是"+this.getType()+",我吃花蜜。"); } }
package com.zxy.Test20160410; /** * 鸵鸟 * @author hsoft3 * */ public class OstrichBirds extends Birds implements Run { public OstrichBirds(String type, String color, double weight) { super(type, color, weight); } @Override public void run() { System.out.println("我是"+this.getType()+",我会奔跑。"); } @Override public void eat() { System.out.println("我是"+this.getType()+",我吃草。"); } }
package com.zxy.Test20160410; public class Test { public static void main(String [] args){ //蜂鸟 Birds hummingBirds = new HummingBird("蜂鸟", "彩虹色", 2.3); hummingBirds.print(); hummingBirds.eat(); Fly f = (Fly) hummingBirds; f.fly(); //鸵鸟 OstrichBirds ostrichBirds = new OstrichBirds("鸵鸟", "灰色", 200.2); ostrichBirds.print(); ostrichBirds.eat(); ostrichBirds.run(); System.out.println("是否会飞=>"+(hummingBirds instanceof Fly)); } }