I was browsing the web in the hope of finding something that will help me build a HuffmanTree and I stumbled across this code from http://rosettacode.org/wiki/Huffman_coding#Java.
I am new to Java and wasn't able to use this as it is way above my level, but I was still intrigued by it (because it is such short and seemingly effective code) and I tried to read through it hoping to at least understand most of it (note: I failed).
But there was one piece of code that caught my attention: the "instanceof" method.
There are 3 classes in my code.
One superclass (HuffmanTree) and two subclasses (HuffmanNode and HuffmanLeaf) and look like this:
abstract class HuffmanTree implements Comparable<HuffmanTree> {
public final int frequency; // the frequency of this tree
public HuffmanTree(int freq) { frequency = freq; }
// compares on the frequency
public int compareTo(HuffmanTree tree) {
return frequency - tree.frequency;
}
}
class HuffmanLeaf extends HuffmanTree {
public final char value; // the character this leaf represents
public HuffmanLeaf(int freq, char val) {
super(freq);
value = val;
}
}
class HuffmanNode extends HuffmanTree {
public final HuffmanTree left, right; // subtrees
public HuffmanNode(HuffmanTree l, HuffmanTree r) {
super(l.frequency + r.frequency);
left = l;
right = r;
}
}
I read a little bit about "instanceof" and as far as I understand it, it tells you if the object is the instance of a certain class (returning a boolean true or false).
And logically a parent can't be the instance of a child.
However, when you write (tree instanceof HuffmanNode), it returns true (tree is a object of the class HuffmanTree) and if I write (tree instanceof HuffmanLeaf) it returns false (logically).
But why does (tree instanceof HuffmanNode) return true when tree is a parent of HuffmanNode?