Hello mcal
I'm glad you feel that way. Lets continue with the instanceof keyword and casting.
Originally Posted by tim
This is all very handy, but what do you do if you want to know what classes you are handling?
The answer to my question is the
instanceof keyword. The
instanceof keyword is used to test if an object is an instance of a class or subclasses of it. The condition:
<object> instanceof <class>
,will give a boolean value. For example:
boolean result1 = dog instanceof Dog;
boolean result2 = dog instanceof Animal;
both result1 and result2 will now be true. Now, lets modify our for loop to display which classes we are working with:
for (int i = 0; i < animals.size(); i++){
Animal animal = animals.get(i);
if (animal instanceof Dog) System.println("A dog goes:");
if (animal instanceof Snake) System.println("A snake goes:");
animal.printSound();
}
I'm going to modify the Dog class a bit:
public class Dog extends Animal{
public Dog(){
super();
}
public void createSound(){
sound = "bark";
}
public void howl(){
sound = "hawooooo";
}
}
Now, Dog has a howl method that is not inherited from Animal. So how will you access it in the for loop? The answer is to use
casting. Casting is when you force one type into another. You can only cast a super class into one of its subclasses. To cast we use the synax:
<subclass here> child = (<subclass here>)parent;
for example, if I know the animal object is a dog then:
Back to the for loop. Let's make the dog howl, and note that snakes cannot howl:
for (int i = 0; i < animals.size(); i++){
Animal animal = animals.get(i);
if (animal instanceof Dog){
Dog castedDog = (Dog)animal; // dog can also be used, but lets ignore that for now :)
castedDog.howl();
System.println("A dog goes:");
}
if (animal instanceof Snake) System.println("A snake goes:");
animal.printSound();
}
We can now handle objects in a generic way. On your quiz problem you needed to save data and read it again. That is a real word problem that programmers face all the time.
Object serialization allows you to take an object just as it is and save or load it at will. Object serialization will make it possible to save an entire data structure will multiple fields and sub data structures to be saved and loaded in just a few lines of code.
Are you interested mcal? Please ask if you get stuck or if there is a bug somewhere.
