• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Analyze this code: instanceof

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks buddy, got the code running..
 
Your mind is under my control .... your will is now mine .... read this tiny ad
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic