Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Assignments

 
Sushant Kaushik
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code is from ExamLab-



Line1 is giving compilation error.

When I am removing final keyword from class C then there is no compilation error. How final keyword is affecting Line1.

Thanks,
Sushant
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason why you are getting a compiler error is because the class C is final, and it doesn't implement Runnable. This is enough for the compiler to figure out that a reference of type C can never point to an object of a class implementing Runnable. If C is not final, then it is possible that you could declare something like:
class D extends C implements Runnable {
}
Then, you could do:
C c = new D(); // c is a C reference pointing to an object of a class that implements Runnable.
But since C is final, this can never happen and the compiler will let you know.

The same goes for casting a reference of type C[] to Runnable[].
 
geeta vemula
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the above example if i remove the final keyword for class c then only line 2 and line 3 are giving classcast exception at runtime as Runnable is not A. Then why not array assingment is showing any exception? Confused with this.. please help..
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Geeta,

That is because ca doesn't point to any object (ca has been assigned null to denote that it doesn't point to any object.) You can only get a ClassCastException based on the type of the actual object pointed to, but since there are no objects involved, that won't happen in this case. Let me know if this doesn't make things clear.

EDIT: To make things more clear, notice that you can assign null to any reference type. You can consider the literal null to be an acceptable value for any reference type.
 
geeta vemula
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah i got it here..Thanks for that.
But this type of questions always confuse me..

Geeta.V
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, these questions are confusing for most people. With practice you can make them less confusing.
 
Sushant Kaushik
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ruben, Its clear now
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That sounds great, keep it up.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic