Hey everyone~! I am having a major issue understanding class casting. I thought I understood it, but I found 2 problems in my Barron's book that seem to contradict in their explanations. Can someone please explain the distinction between these two problems???
Problem 1:
Bird = Super class
Owl = Subclass of Bird
Parrot = Subclass of Bird
Parakeet = Subclass of Parrot
public class BirdStuff
{
public static void printName(Bird b)
{ /* Implementation Not Shown */}
public static void printBirdCall(Parrot p)
{ /* Implementation Not Shown */}
public static void main(String[] args)
{
Bird bird = new Parrot();
printName(bird);
printBirdCall(bird);
}
}
The code above causes an error because even though bird takes a Parrot object, it is treated like a bird and thus cannot be used in the printBirdCall() method without first being cast down to a Parrot using the syntax printBirdCall((Parrot) bird).
Problem 2:
Consider these declarations:
Integer intOb = new Integer(3);
Object ob = new Integer(4);
Double doubOb = new Double(3.0);
if (intOb.compareTo(ob)<0)...
The code above does not cause an error, because ob contains an Integer object, so when intOb calls its compareTo() method that accepts an Integer parameter, this will work correctly.
My confusion: Isn't one of them wrong??? If intOb calls compareTo() correctly on ob which is of type object, shouldn't the printBirdCall() be called correctly on bird, since it is an instance of Parrot? Is there a distinction to be made between these 2 cases??? Help!!!