简体   繁体   中英

I have question about the Polymorphism in Java

I define class variable map

private Map<Double, Integer> map = new TreeMap<>((o1, o2)->-o1.compareTo(o2));

But when I can't call its method in class method

private void inOrder(BalancedBinaryTree.TreeNode root, double target, int k){
    ...
    map.pollFirstEntry();
    ...
}

But when I Fix it into

private TreeMap<Double, Integer> map = new TreeMap<>((o1, o2)->-o1.compareTo(o2));

Now I can call the method of TreeMap, why is that? Why the Polymorphism loses in this situation?

You are defining a variable of type Map using the TreeMap implementation. In this case, you will be able to call just the methods that are define in Map. In the second case, you are defining a TreeMap variable so you can call all the extra methods you mentioned.

If, in the first case you would cast to TreeMap you would be able to call the method as well.

Something like this:

import java.util.Map;
import java.util.TreeMap;

public class TreeMapCheck {
        static Map<Integer, Double> map = new TreeMap<>();
        static TreeMap<Integer,Double> treeMap = new TreeMap<>();

    public static void main(String[] args) {
        ((TreeMap)map).pollFirstEntry();
    }
}

This kind of approach would fail if there is a difference implementation than the one you would expect, so one can protect herself/himself from that checking whether the given instance is a TreeMap, like this:

public static void main(String[] args) {
    ((TreeMap)map).pollFirstEntry();

    if (map instanceof TreeMap) {
        ((TreeMap)map).pollFirstEntry();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM