• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof question?

 
Bashar Ayyash
Ranch Hand
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");

System.exit(0);
}

}

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
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Max Habibi
town drunk
( and author)
Sheriff
Posts: 4118
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks,
M
[ June 25, 2004: Message edited by: Max Habibi ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic