"I said 2 as we are checking if the object is a dog; as dog is the class with the bark method in it, if it is then we call it which will print out :s"
Your rationale is correct, but that's not the way it works.
Java is an static typed language that means, the validity of the methods an object may respond to is verified at compile time.
You may think the check:
if( a instanceof Dog )
Would do, but actually it doesn't. What the compiler do is check against the "interface" of the declared type ( Animal in this case ). The "interface" is composed of the methods declared on the Animal class.
If the bark() method is not defined in the super class Animal the compiler says: "Hey, that won't work".
This is helpful, because "sometimes" we make typos while coding ( typing barck() instead for instance )
If the compiler doesn't not warn us about this, you would have to find it at "runtime" and not always with a clear message ( for instance javascript in IE says something like "unexpected object" )
Still, static typed language like java allow us to force the call. In this case it is using the "cast" operator ()
Like this
1. Animal a = new Dog();
2. if (a instanceof Dog){
3. Dog imADog = ( Dog ) a;
4. imADog.bark();
5. }
In line 3 your are "casting" to a Dog type so the compiler may check if bark is a valid message.
This is an instruction to to compiler saying "Hey I'm the programmer here, I know what I'm doing". And the compiler, checks, Ok, dog, can receive the message bark(), proceed. Yet, if in runtime the animal is not a dog, a runtime exception will raise.
The cast could also be abbreviated like:
if( a instanceof Dog ) {
((Dog)a).bark();
}
That will run.
So, the correct answer is 4: "the call to bark causes a compile time error"
I hope this helps.