When to implement an interface and when to extend a superclass?

后端 未结 11 818
遇见更好的自我
遇见更好的自我 2020-11-30 04:41

I\'ve been reading a lot about interfaces and class inheritance in Java, and I know how to do both and I think I have a good feel for both. But it seems that nobody ever rea

11条回答
  •  春和景丽
    2020-11-30 05:17

    No one?

    http://mindprod.com/jgloss/interfacevsabstract.html

    EDIT: I should supply more than a link

    Here's a situation. To build on the car example below, consider this

    interface Drivable {
        void drive(float miles);
    }
    
    abstract class Car implements Drivable { 
        float gallonsOfGas;
        float odometer;
        final float mpg;
        protected Car(float mpg) { gallonsOfGas = 0; odometer = 0; this.mpg = mpg; }
        public void addGas(float gallons) { gallonsOfGas += gallons; }
        public void drive(float miles) { 
            if(miles/mpg > gallonsOfGas) throw new NotEnoughGasException();
            gallonsOfGas -= miles/mpg;
            odometer += miles;
        }
    }
    
    class LeakyCar extends Car { // still implements Drivable because of Car
        public addGas(float gallons) { super.addGas(gallons * .8); } // leaky tank
    }
    
    class ElectricCar extends Car {
        float electricMiles;
        public void drive(float miles) { // can we drive the whole way electric?
             if(electricMiles > miles) {
                 electricMiles -= miles;
                 odometer += miles;
                 return;                 // early return here
             }
             if(electricMiles > 0) { // exhaust electric miles first
                 if((miles-electricMiles)/mpg > gallonsOfGas) 
                     throw new NotEnoughGasException();
                 miles -= electricMiles;
                 odometer += electricMiles;
                 electricMiles = 0;
             }
             // finish driving
             super.drive(miles);
        }
    }
    

提交回复
热议问题