File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes instanceof question? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "instanceof question?" Watch "instanceof question?" New topic

instanceof question?

Bashar Ayyash
Ranch Hand

Joined: Jun 24, 2004
Posts: 44
Hi guys,
I need explanation for the following marked line, which is in test2 class:

public class InstanceofClass {
public static void main(String[] args) {
test2 t = new test2();
if(t instanceof Object)
System.out.println("t instance of Object");
if(t instanceof test1)
System.out.println("t instanceof test1");
if(t instanceof testInterface)
System.out.println("t instanceof testIterface");



class test2 extends test1{
public test2(){
if(this instanceof test1)
System.out.println("test2 instanceof test1");

class test1 implements testInterface{
public test1(){
if(this instanceof test2)//need explanation ???
System.out.println("test1 instanseof test2");
public void output(){
System.out.println("interface method");

interface testInterface{
void output();

When I compile and run the program i get:

test1 instanseof test2
test2 instanceof test1
t instance of Object
t instanceof test1
t instanceof testIterface

Why test1 instanceof its subclass?
David Moose

Joined: Jun 11, 2004
Posts: 4
Because test2 object is being created.
I think this behaviour is related to the Behavior of polymorphic methods
inside constructors. Consider
class Base {
Base() { method();}
void method() { System.out.println("Base method");}
class Derived extends Base{
void method() { System.out.println("Derived method");}
public static void main(String args[]) {
Derived d = new Derived();

This will print "Derived method".
Pal Sudarshan
Ranch Hand

Joined: Jun 10, 2004
Posts: 52
Max Habibi
town drunk
( and author)

Joined: Jun 27, 2002
Posts: 4118
Hi Bashar,

Welcome to the ranch, and I'm glad you got your question answered

I wanted to tell you that we require members to adhere to a naming policy. That is, a first name followed by a last name, and it should not be a name I recognize, so Don Juan is out. As a matter of fact, we love to encourage member to use their real names. Please modify your name accordingly when you have time.

[ June 25, 2004: Message edited by: Max Habibi ]

Java Regular Expressions
I agree. Here's the link:
subject: instanceof question?
It's not a secret anymore!