my dog learned polymorphism*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "instanceof question?" Watch "instanceof question?" New topic
Author

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");

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

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)
Sheriff

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.

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

Java Regular Expressions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof question?
 
Similar Threads
Code within a curly braces
Errors in Master Exam?!
[Comparable] problem with ording classes
instanceOf - most useless operator ever?
Understanding inheritance