0

i saw some code where HashTable(collection) value is passed as interface

public class Channels {

    private static final Hashtable<String, IChannel> channels =
        new Hashtable<String, IChannel>();

    public void putChannel(String serviceChannelName, IChannel channel) {
        channels.put(serviceChannelName, channel);
    }
}

like

public interface IChannel {

    public void start();

    public void stop();
}

what exectly going to use and and how it can possible to pass interface object (while we can not create interface object.?? please help me

Jens
  • 67,715
  • 15
  • 98
  • 113
  • 3
    I suggest you read a tutorial on interfaces - this is just one example of using them, but once you've got the bigger picture, everything will make more sense. Basically, you're not passing an "interface object" - you're passing a reference to an object which is an instance of some class which *implements* the interface. – Jon Skeet Dec 17 '14 at 14:06
  • "to pass interface object" You have to use a class that implements IChannel. – emecas Dec 17 '14 at 14:06
  • possible duplicate of [What does it mean to "program to an interface"?](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – Raedwald Dec 17 '14 at 21:09

2 Answers2

3

You're not passing an interface object, but an interface implementation, which gives you room to put different implementations of the interface to the map.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
2

You should pass instances of concrete type, which implements IChannel interface.

Example:

Definition of concrete type:

public class ChannelImpl implements IChannel {
    public void start() { 
        /* implementation here */ 
    }

    public void stop() { 
        /* implementation here */ 
    }
}

and then use your implementation:

new Channels().put("Channel1", new ChannelImpl()); 

To learn how to use this, you should read about OOP.

pbespechnyi
  • 2,251
  • 1
  • 19
  • 29