Tanveer said:
One of my function returns java.lang.Object type of object
My problem is:
There is a method called getData() as:
java.lang.Object getData();
but i want to typecast it as: PDataNode
I want to do something like:
PDataNode node1 = temp.getData();
But this is not possible, because , PDataNode is not of type
java.lang.Object, so i did
PDataNode node1 = (PDataNode) temp.getData();
Isn't this allowed in Java.
I thought , concepts like typecasting will surely work in java.
Though it gets compiled but gives runtime error.
I am beginner in Java, so please consider my basic question as well...
Hint: Instead of saying "runtime error" and making us all
guess which of the many possible errors it might have been,
consider showing us the actual error message. If you were a
doctor, would you prefer to hear a patient complain "Doc, I
feel bad" or "Doc, I've been vomiting since midnight and I'm
running a fever and my vision is blurry?" Give the diagnostician
all the information you can.
Since you force me to guess, I'll guess that "runtime error"
was either a NullPointerException or a ClassCastException -- if
it was actually something else, you have only yourself to blame
for concealing its nature.
If the error was NullPointerException, it means that `temp'
had the value `null' at the moment when you tried to call its
getData() method. That is, `temp' was a variable capable of
referring to an object (of a type that has a getData() method),
but at the time you tried the call it was not actually referring
to anything at all. You can ask someone on the street "Excuse
me, what time is it?" but if there's nobody there and you ask
the question of thin air you can't expect anything good to happen.
If the error was ClassCastException, it means that getData()
returned a reference to an Object that didn't happen to be a
PDataNode object. It may have returned a reference to a String
or to an Integer or to a YourHonorIObject, but it didn't return
a reference to a PDataNode. You cannot (as in C) simply tell
the system to pretend that an object is of some unrelated type;
casts are checked for validity at run-time, and "punning" casts
are disallowed. When you write a cast, you say "Listen, Java,
I know getData() only promises to return an Object, but I happen
to know that the Object is actually a PDataNode." Java replies
"Trust, but verify" -- and if you lied to it, ClassCastException.