I am a bit confused on the purpose of declaring instances as specific types. For example,
Integer intOb1 = new Integer(3);
Object intOb2 = new Integer(4);
I know the type of intOb1 is Integer, and the type of intOb2 is Object, but what does declaring intOb2 as Object allow one to do? Use methods in Object? Can’t you already use those methods as an Integer? Or is the main purpose just to be able to “treat” intOb2 as an Object?
As you can see, I’m befuddled.
This actual isn’t called casting this is an example of polymorphism. Which allows variables to take on different types based on their inheritance relationships with other classes.
For example, suppose you were writing a program to simulate a zoo. You would have a class called
Zooand a class calledAnimal. There are also several classes that extend from theAnimalclass:Lion,Zebra, andElephant.It would be extremely useful to keep all of these objects grouped together in a single list but since they are of different types, i.e:
Lion,Zebra, andElephant, you can’t store them in a single list, you would have to maintain a separate list for each type of animal. This is where polymorphism comes into play.Since each of the classes
Lion,Zebra, andElephantall extend from theAnimalclass we can simply store them in a list of typeAnimal.code example:
Hope this helps, even with a silly example.