Is there more to an interface than having the correct methods

后端 未结 17 675
小鲜肉
小鲜肉 2020-11-22 13:37

So lets say I have this interface:

public interface IBox
{
   public void setSize(int size);
   public int getSize();
   public int getArea();
  //...and so          


        
17条回答
  •  感情败类
    2020-11-22 14:28

    Here is my understanding of interface advantage. Correct me if I am wrong. Imagine we are developing OS and other team is developing the drivers for some devices. So we have developed an interface StorageDevice. We have two implementations of it (FDD and HDD) provided by other developers team.

    Then we have a OperatingSystem class which can call interface methods such as saveData by just passing an instance of class implemented the StorageDevice interface.

    The advantage here is that we don't care about the implementation of the interface. The other team will do the job by implementing the StorageDevice interface.

    package mypack;
    
    interface StorageDevice {
        void saveData (String data);
    }
    
    
    class FDD implements StorageDevice {
        public void saveData (String data) {
            System.out.println("Save to floppy drive! Data: "+data);
        }
    }
    
    class HDD implements StorageDevice {
        public void saveData (String data) {
            System.out.println("Save to hard disk drive! Data: "+data);
        }
    }
    
    class OperatingSystem {
        public String name;
        StorageDevice[] devices;
        public OperatingSystem(String name, StorageDevice[] devices) {
    
            this.name = name;
            this.devices = devices.clone();
    
            System.out.println("Running OS " + this.name);
            System.out.println("List with storage devices available:");
            for (StorageDevice s: devices) {
                System.out.println(s);
            }
    
        }
    
        public void saveSomeDataToStorageDevice (StorageDevice storage, String data) {
            storage.saveData(data);
        }
    }
    
    public class Main {
    
        public static void main(String[] args) {
    
            StorageDevice fdd0 = new FDD();
            StorageDevice hdd0 = new HDD();     
            StorageDevice[] devs = {fdd0, hdd0};        
            OperatingSystem os = new OperatingSystem("Linux", devs);
            os.saveSomeDataToStorageDevice(fdd0, "blah, blah, blah...");    
        }
    }
    

提交回复
热议问题