Ruchika Si wrote:According to k&B Java 5 table 4-1 pg 286 if first operand is ref of Foo[] and instanceof operand is Foo Bar Face, it will return false but it is returning true. Can you explain?
interface Face{}
class Bar implements Face{}
public class Foo extends Bar{
public static void main(String [] args){
Foo[] f = new Foo[5];
if (f instanceof Foo[]) System.out.println("true"); // Prints true
// if (f instanceof Foo) System.out.print("1 "); // it does not compile
}
}
What should I do fix the code?
Thanks
Ikpefua wrote:
Hello Ruchika, I want to try and help by explaining my understanding of arrays based on what I studied in the K & B book.
should be read as follows: "Declaration of a reference variable f of that refers to an object of type Foo".
should be read as follows: "Declaration of a reference variable f that refers to an ARRAY OBJECT that holds a total of 5 'f' of type Foo".
Hint: Remember that an array[] is an object whose principal duty -amongst others- is to hold reference variables of a particular type,
so this '[5]' means: "Hey I am an Object (NOT A FOO OBJECT), and I contain a total of 5 'f' of type Foo".
Summary: An array Object is NOT the same thing as a Foo Object. (Precisely what the instanceof
test is telling you)
I hope this helps, sincerely speaking arrays gave me headache at a time till I got to understand it.