爪哇国新游记之五----继承与接口

// Car,Bus,Truck的基类
public
class Vehicle{ protected int wheelCount; }
// 所有类共同的接口
public interface Countable{ public final int a=9; public int getWheelCount(); } public class Bus extends Vehicle implements Countable{ public Bus(){ wheelCount=6; } @Override public int getWheelCount() { return wheelCount; } } public class Car extends Vehicle implements Countable{ public Car(){ wheelCount=4; } @Override public int getWheelCount() { return wheelCount; } } public class Truck extends Vehicle implements Countable{ public Truck(){ wheelCount=10; } @Override public int getWheelCount() { return wheelCount; } } public class Motor implements Countable{ @Override public int getWheelCount() { return 2; } } public class Tank implements Countable{ @Override public int getWheelCount() { return 0; } } public class Test{ public static void main(String[] args){ // 统一了诸类接口,所有实例都可放入一个数据结构,方便存储和计算 Countable[] arr=new Countable[7]; if(arr[1]==null){ System.out.println("arr[1]==null"); } arr[0]=new Bus(); arr[1]=new Car(); arr[2]=new Motor(); arr[3]=new Tank(); arr[4]=new Truck(); arr[5]=new Car(); arr[6]=new Car(); int sum=0; for(int i=0;i<arr.length;i++){ // 同一接口强制子类实现固定方法,方便了代码书写和测试 sum+=arr[i].getWheelCount(); } System.out.println("Sum="+sum); for(Countable c:arr){ // 同一接口强制子类实现固定方法,方便了代码书写和测试 sum+=c.getWheelCount(); } System.out.println("Sum="+sum); } }

你可能感兴趣的:(接口)