Re: Parentheses issue
Andrew wrote:
This is an order of operations issue. It would also help to know
whether the error you got was a compile-time error or a runtime error.
(I'm not sure if you said or not.)
If it was a compile-time error, read this, but you might want to read
it anyway:
Sometimes you can use
(Type)object
without having to put an extra set of parentheses around the whole
thing, like if you are saying
Type1 object2 = (Type1)object1;
but since the casting operation happens in the order it does, to do
most other operations on the casted object, you will need another set
of parentheses, like in the following example:
if(object1 instanceof Type1)
if(((Type1)object1).booleanFunction())
doSomething();
Another common case is getting an item out of a list:
if(list.get(index) instanceof Type1)
((Type1)list.get(index)).doSomething();
OTHERWISE, if it was a runtime error, read this (and you might want to
read it anyway):
The && operator evaluates the expressions on both sides. Even if the
first side is false (and therefore it would logically return false
regardless of the second side's value) the second side will still be
evaluated. Thus, in a case such as
if(object1 instanceof Type1 &&
((Type1)object1).someBooleanFunction())
doSomething();
the Java Virtual Machine will come across an error if the object is not
of the required type, because it will try to evaluate the second
expression.
The way to solve this is to do either this
if(object1 instanceof Type1)
if(((Type1)object1).booleanFunction())
doSomething();
or, if you are feeling bold and know or are ready to learn the ternary
operator:
if(object1 instanceof Type1 ? ((Type1)object1).booleanFunction() :
false)
doSomething();
I hope this helps.
Actually, you are wrong about the &&... && is a short-circuting
operator, & is not.
<sscce>
public class Test {
private static boolean aCalled = false;
private static boolean bCalled = false;
public static void main(String[] args) {
if (a() && b()) {
System.out.println("a() and b() returned true");
}
System.out.println("aCalled:" + aCalled + ", bCalled: " +
bCalled);
aCalled = false;
bCalled = false;
if (a() & b()) {
System.out.println("a() and b() returned true");
}
System.out.println("aCalled:" + aCalled + ", bCalled: " +
bCalled);
}
public static boolean a() {
aCalled = true;
return false;
}
public static boolean b() {
bCalled = true;
return false;
}
}
</sscce>
<output>
aCalled:true, bCalled: false
aCalled:true, bCalled: true
</output>
The trouble with the code the OP presented was indeed the compile
error.
(MyType)expression will cast the result of "expression" to MyType,
where as ((MyType)object).member will cast object to MyType, and then
access member.
Hope this helps,
Daniel.