i know how to determine if x instanceof aClass.
if x is not an instanceof aClass, how can i tell if it it will give me a compiler error or run time error.

Consider the following question~

interface I {
...
}
class A {
...
}
class B extends A {
...
}
class C implements I {

}
class D extends C {
...
}
and given the following declarations:
A aRef;
B bRef;
C cRef;
D dRef;
I iRef;
I i2Ref;
For each of the following statements circle all correct outcomes:
a. aRef = new B(); a) compiler error b) compiles c) can cause a runtime error
b. bRef = new A(); a) compiler error b) compiles c) can cause a runtime error
c. iRef = new C(); a) compiler error b) compiles c) can cause a runtime error
d. i2Ref = new D(); a) compiler error b) compiles c) can cause a runtime error
e. cRef = new I(); a) compiler error b) compiles c) can cause a runtime error
f. aRef = new C(); a) compiler error b) compiles c) can cause a runtime error
In the following, assume the right-hand side has been correctly instantiated to some legal value chosen
from the classes A, B, C, D but possibly different from the ones listed in (a) through (f).
g. bRef = (B)aRef; a) compiler error b) compiles c) can cause a runtime error
h. iRef = i2Ref; a) compiler error b) compiles c) can cause a runtime error
i. cRef = iRef; a) compiler error b) compiles c) can cause a runtime error
j. dRef = (D)iRef; a) compiler error b) compiles c) can cause a runtime error

Recommended Answers

All 2 Replies

Be clear with your questions, instanceof is a specific java statement that can be used (for example) in the following way:

if (x instanceof y){
   System.out.println("Cool");
} else System.out.println("No runtime error or compiler error here.");

And btw, I did understand your question after I read the quote, I'm just saying to avoid confusing language. Anyway, you can tell what kind of error it will produce by designing a program and attempting to run it. If it won't run it is a compiler error. If it runs but crashes its a runtime error. But with a little knowledge of inheritance you can probably deduce that if you try to instantiate one type (for example, class Whatever) and do something like Whatever c = new OtherThing .. where OtherThing is not a child of Whatever in the inheritance hierarchy, then it should generate a compiler error. Again, one test program is worth a thousand expert opinions, but read about inheritance and you will begin to understand. I could point out one by one what happens in your example above, but that won't help you learn nearly as much as writing a test program and seeing what an actual compiler does after reading a little bit about Java inheritance.

commented: helps a lot! +1

thanks... that helps me a lot !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.