File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof

 
Harshad Patel
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 328
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What was the question, and what makes you confused about it?
 
Harshad Patel
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 328
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic