0

I have a strange class that has a interface object as attribute. What does it mean?

public interface Acceptor{
    public void accept(Thing thing);
    public boolean hasSpace();
}

public class Box{
    private final Acceptor acceptor;
    public Box(Acceptor acceptor){
        this.acceptor = acceptor; 
    }
 
    public void acceptor(Thing thing){
         acceptor.accept(thing);
    }
   
    public void hasSpace(){
         return acceptor.hasSpace();
    }
}

Say I want to create an instance of Box, how?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Zhijie Xia
  • 27
  • 6
  • 4
    Does this answer your question? [What does it mean to "program to an interface"?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – OH GOD SPIDERS Jan 21 '21 at 13:09
  • "I want to create an instance of Box, how?" <- In short, you use the constructor and pass any object that imlements the interface `Acceptor` as a parameter. – OH GOD SPIDERS Jan 21 '21 at 13:14

2 Answers2

2

It means whatever object you pass to the Box constructor must implement the Acceptor interface. To create a Box object, you'd need to do something like this:

Acceptor a = new Foo(); // assuming Foo implements Acceptor
Box b = new Box(a);

Whatever else Foo does, as long as it implements the Acceptor interface, it will be guaranteed to have everything Box needs when it calls Acceptor methods on the object passed to the Box constructor.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

You can use anonymous class also:

        Box box=new Box(new Acceptor(){
            @Override
            public void accept(Thing thing) {
                //...
            }

            @Override
            public boolean hasSpace() {
                //...
                return true;
            }          
        });

more about anonymous classes

yuri777
  • 377
  • 3
  • 7