Inheritance - Instanceof Flashcards
What will the following expression return?
(s instance of java.util.Date)
Assume ‘s’ is a variable of class java.lang.String
Nothing, it won’t even compile.
The compiler knows ‘s’ can NEVER refer to java.util.Date, so it won’t accept this code.
Is the following code valid?
Short k = new Short(4)
No, there is no constructor for Short that takes an int.
Can the left operand of the instanceof
operator be a primitive?
i.e.:
short s = 4;
System.out.println(s instance of Short);
No!
It must be a reference variable.
What is the left-hand operand of an instanceof statement?
A reference variable.
What is the right-hand operand of instanceof?
A reference type name (class, interface, or enum)
What can be compared with the == operator?
Two primitives. Also, a numeric primitive and a primitive wrapper.
What cannot be compared with the == operator?
Two wrappers of different types. For example, you cannot compare an Integer and a Short
Will the following code compile?
Short k = 9; Integer i = 9; System.out.println(k == i);
No, they must have an IS-A relationship among themselves.
Will the instanceof operator return true if the right-hand side is a super class?
i.e. for class reference foo (foo instanceof Object)
Yes.
The right hand side will return true even if it is a super class.
If a.equals(b) returns true, b instanceof ClassOfA must always be true.
Right?
Not necessarily.
equals ( ) can be overridden.