Whizzil
Whizzil

Reputation: 1364

Cast exception?

So im getting this ClassCastException when trying to cast my Node<T> to my AVLNode<T>. No idea why.

Here is where it throws an exception.

Node<Integer> n1 = new Node<Integer>(3, null);
    AVLNode<Integer> n2 = (AVLNode<Integer>) n1;

How the classes look...

public class Node<T extends Comparable<T>> {

public Node<T> right;

public Node<T> left;

public Node<T> parent;

public T data;

public Node(T data, Node<T> parent) {
    this.data = data;
    this.parent = parent;
} // ...

And the other class in separate file:

public class AVLNode<T extends Comparable<T>> extends Node<T> {

public int height = 1;

public AVLNode(T data, Node<T> parent) {
    super(data, parent);
} //...

Error message: Exception in thread "main" java.lang.ClassCastException: custom.trees.Node cannot be cast to custom.trees.AVLNode

Upvotes: 0

Views: 252

Answers (3)

Sainath S.R
Sainath S.R

Reputation: 3306

Your node is a SuperClass of AVLNode. You have misunderstood how Java casting works, you cannot make such casts as such. The only situation where you should cast is, if you have a node reference that points to AVLnode Object, you can say

Node n1=new AVLNode();
AVLNode n2=(AVLNode)n1;

where, since the object type is the same, the reference can be casted.

What you are trying here is to cast a Node (parent class) Object's Reference to a AVLNode (Sub-Class) reference, which simply isn’t possible!

Upvotes: 2

giorashc
giorashc

Reputation: 13713

You are down casting Node to AVLNode. Since n1 is an instance of Node it does not contain the extra implementation provided by AVLNode and this is why you get the casting exception to prevent you from executing a method of AVLNode on a Node instance.

Upvotes: 2

Evan Knowles
Evan Knowles

Reputation: 7501

Basically, because a Node is not a AVLNode - you created it a Node, so it's a Node. If you'd created it as a AVLNode you could cast it to a Node, but not the other way round.

Upvotes: 6

Related Questions