• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Analyze this code: instanceof

 
Mickey Smith
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone point out what is wrong with this code:

class A {

A(){
}

}

class B extends A {

B(){
}


}



class TestInstanceof {

public static void main(String a[]){

A a = new A();
B b = new B();

if(a instanceof b){

System.out.println("A is instance of B");

} else {

System.out.println("A is not instance of B");

}

if(b instanceof a){

System.out.println("B is instance of A");

} else {

System.out.println("B is not instance of A");

}



}



}

I get a compliation error:

C:\TestInstanceof.java:26: a is already defined in main(java.lang.String[])
A a = new A();
^
C:\TestInstanceof.java:29: cannot resolve symbol
symbol : class b
location: class TestInstanceof
if(a instanceof b){
^
C:\TestInstanceof.java:39: cannot resolve symbol
symbol : class a
location: class TestInstanceof
if(b instanceof a){
^
3 errors

Tool completed with exit code 1
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15448
42
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
C:\TestInstanceof.java:26: a is already defined in main(java.lang.String[])
A a = new A();


Well, the error message says it all. You already have something else called "a". Look closely at the first line of your main() method:

public static void main(String a[]){

Can you see that you already have a variable named "a" there?

About the other errors:

1. Java is case-sensitive. So "b" is not the same as "B".
2. "instanceof" does not take two objects as parameters. It takes an object and a class name - that's why the compiler says it cannot find class b or class a.
 
Mickey Smith
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks buddy, got the code running..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic