Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof Problem

 
Andreas Sandberg
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Folks,

This question comes out of the K&B book, self test question #2 on Pg.195.
The question is as follows:

2. 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 independnently, 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 answer is B and D, but why not F? I get a compile time error when inserting the expression. String is a subclass of Object so why can't I use the instanceof operator? Although I know they are entirely different objects, isn't that the whole point of instanceof. It should tell me if they are the same type of object so then I can make an implicit cast. Like when you overide the equals method. Any clarrification is appreciated.

Thanks,

Andreas
[ October 06, 2005: Message edited by: Andreas Sandberg ]
 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

instanceof operator flags a compile time error if the object is not at all related to the class its being compared in any manner. Here in your example t which is an object of Ticker class is ofcourse a subclass of Component class, but then there is no inheritance relation between Ticker and a String.

Same is the case with String and StringBuffer.

String s;
boolean b=s instanceof StringBuffer; //compile time error

it says
main.java:10: inconvertible types
found : java.lang.String
required: java.lang.StringBuffer
boolean b=s instanceof StringBuffer;
^
1 error

Hope this helps
 
A Kumar
Ranch Hand
Posts: 980
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Have a look at this...



JLS


[ October 06, 2005: Message edited by: A Kumar ]
 
Andreas Sandberg
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Muchos gracias. Still think it would make sense to compare two reference types with the instanceof operator and have it return false rather than a compile time exception though.


a
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic