aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes instanceof Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "instanceof" Watch "instanceof" New topic
Author

instanceof

Harshad Patel
Greenhorn

Joined: Aug 16, 2004
Posts: 5
Im slightly confused about this question (from one of the popular books)

...
class Ticker extends Component {
public static void main (String[] args) {
Dmitry Melnik
Ranch Hand

Joined: Dec 18, 2003
Posts: 328
What was the question, and what makes you confused about it?
Harshad Patel
Greenhorn

Joined: Aug 16, 2004
Posts: 5
sorry posted too soon

Given the following,

1. import java.awt.*;
2. class Ticker extends Component {
3. public static void main (String [] args) {
4. Ticker t = new Ticker();
5.
6. }
7. }

which two of the following statements, inserted independently, could legally be inserted into
line 5 of this code? (Choose two.)
A. boolean test = (Component instanceof t);
B. boolean test = (t instanceof Ticker);
C. boolean test = t.instanceof(Ticker);
D. boolean test = (t instanceof Component);
E. boolean test = t.instanceof(Object);
F. boolean test = (t instanceof String);

The correct answers are B and D
and the author explains that F is incorrect because the String class is not in the hierarchy of the t object.

But surely it is ok and legal to insert F at line 5 ?
as the boolean test will result in false - rather than true ?

cam anyone clear that up for me ?
Thanks
Harshad
Dmitry Melnik
Ranch Hand

Joined: Dec 18, 2003
Posts: 328
But surely it is ok and legal to insert F at line 5 ?
as the boolean test will result in false - rather than true ?


You'll get a compile-time error, if type of the left-hand operand of instanceof can not be converted to the right-hand type.
Abbu Rahman
Ranch Hand

Joined: Jan 05, 2004
Posts: 46
let me try,

class XYZClass
{
/************************************/
}

x instanceof XYZClass (= true)
if x refres to an object which is of type XYZClass or any of its subclasses.

x instanceof XYZClass (= false)
if x refres to an object which is super calss of XYZClass.

example:
Object obj = new Object();
obj instanceof XYZClass = false //obj is superclass of XYZClass


String x = "";
x instanceof XYZClass (= error)
does not compile , because String and XYZClass not at all related.
neither String is subclass to XYZClass nor is it superclass of XYZClass.


hope that helps,
Rafay
[ August 20, 2004: Message edited by: Abdul Rafay Mansoor ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof