Is there more to an interface than having the corr

2018-12-31 19:31发布

So lets say I have this interface:

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

And I have a class that implements it:

public class Rectangle implements IBox
{
   private int size;
   //Methods here
}

If I wanted to use the interface IBox, i can't actually create an instance of it, in the way:

public static void main(String args[])
{
    Ibox myBox=new Ibox();
}

right? So I'd actually have to do this:

public static void main(String args[])
{
    Rectangle myBox=new Rectangle();
}

If that's true, then the only purpose of interfaces is to make sure that the class which implements an interface has got the correct methods in it as described by an interface? Or is there any other use of interfaces?

17条回答
低头抚发
2楼-- · 2018-12-31 20:23

Don't forget that at a later date you can take an existing class, and make it implement IBox, and it will then become available to all your box-aware code.

This becomes a bit clearer if interfaces are named -able. e.g.

public interface Saveable {
....

public interface Printable {
....

etc. (Naming schemes don't always work e.g. I'm not sure Boxable is appropriate here)

查看更多
还给你的自由
3楼-- · 2018-12-31 20:24

The purpose of interfaces is polymorphism, a.k.a. type substitution. For example, given the following method:

public void scale(IBox b, int i) {
   b.setSize(b.getSize() * i);
}

When calling the scale method, you can provide any value that is of a type that implements the IBox interface. In other words, if Rectangle and Square both implement IBox, you can provide either a Rectangle or a Square wherever an IBox is expected.

查看更多
君临天下
4楼-- · 2018-12-31 20: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...");    
    }
}
查看更多
永恒的永恒
5楼-- · 2018-12-31 20:30

Interfaces are a way to make your code more flexible. What you do is this:

Ibox myBox=new Rectangle();

Then, later, if you decide you want to use a different kind of box (maybe there's another library, with a better kind of box), you switch your code to:

Ibox myBox=new OtherKindOfBox();

Once you get used to it, you'll find it's a great (actually essential) way to work.

Another reason is, for example, if you want to create a list of boxes and perform some operation on each one, but you want the list to contain different kinds of boxes. On each box you could do:

myBox.close()

(assuming IBox has a close() method) even though the actual class of myBox changes depending on which box you're at in the iteration.

查看更多
何处买醉
6楼-- · 2018-12-31 20:33

One of the many uses I have read is where its difficult without multiple-inheritance-using-interfaces in Java :

class Animal
{
void walk() { } 
....
.... //other methods and finally
void chew() { } //concentrate on this
} 

Now, Imagine a case where:

class Reptile extends Animal 
{ 
//reptile specific code here
} //not a problem here

but,

class Bird extends Animal
{
...... //other Bird specific code
} //now Birds cannot chew so this would a problem in the sense Bird classes can also call chew() method which is unwanted

Better design would be:

class Animal
{
void walk() { } 
....
.... //other methods 
} 

Animal does not have the chew() method and instead is put in an interface as :

interface Chewable {
void chew();
}

and have Reptile class implement this and not Birds (since Birds cannot chew) :

class Reptile extends Animal implements Chewable { } 

and incase of Birds simply:

class Bird extends Animal { }
查看更多
登录 后发表回答