0

I was reading the tutorial from https://docs.oracle.com/javase/tutorial/java/generics/types.html.

Code:

public interface Pair<K, V> {
    public K getKey();
    public V getValue();
}

public class OrderedPair<K, V> implements Pair<K, V> {

    private K key;
    private V value;

    public OrderedPair(K key, V value) {
    this.key = key;
    this.value = value;
    }

    public K getKey()   { return key; }
    public V getValue() { return value; }
}

But above code, i can't grasp.

 Pair<String, Integer> p1 = new OrderedPair<String, Integer>("Even", 8);
    Pair<String, String>  p2 = new OrderedPair<String, String>("hello", 
   "world");

It seems like creating an object of Interface, but as per my understanding of OOP in c++, it's impossible to create an object of Abstract Class(My understanding is that Interface is somehow like Abstract Class). Needed a more specific answer "How is it possible to create such object?"

Edited

As i was suggested to view answer at Instantiating interfaces in Java.

What's the differences between instantiation of object in following two cases:

Pair<String, Integer> p1 = new OrderedPair<String, Integer>("Even", 8);
OrderPair<String, Integer> p2 = new OrderedPair<String, Integer>("Even", 8);

1 Answers1

1

You're actually not instantiating an interface. You are instantiating a class which implements the interface, then saving the object to a variable of the interface's type.

Instantiating the interface would be something like this, which you cannot do.

Pair<String, Integer> p1 = new Pair<>("Even", 8);

However, you can make it an anonymous class.

Pair<String, String> p2 = new Pair<String, String>() {
    @Override
    public String getKey() {
        return "hello";
    }

    @Override
    public String getValue() {
        return "world";
    }
};
killjoy
  • 3,665
  • 1
  • 19
  • 16