Reputation: 105
class A {
}
class B extends A {
}
class Main {
public static void main(String[] args) {
B b1 = new B();
B b2 = new B();
A a = b1;
A c = (A) b2;
}
}
Is there any difference between a
and c
? b1
is directly referenced and b2
is upcasted to A
and then referenced to c
of type A
.
Upvotes: 2
Views: 63
Reputation: 1075309
There's no need for the cast there. In an assignment context, a widening reference conversion is allowed. No need for a casting context. (Now, if it were a narrowing reference conversion, you'd have to do that explicitly.)
Upvotes: 3
Reputation: 312086
The cast is redundant. b2
gets assigned to c
regardless, and invoking any methods on it will invoke the methods of B
if they exist.
Upvotes: 2