Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

OCA Practise Question on inheritance  RSS feed

 
Akash Trivedi
Greenhorn
Posts: 18
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello guys, my confusion is as follows :

At line labelled //1: Is 'a1' is also of type 'A' ?. I don't understand the notion of it.

At line labelled //2: Are 'a1' and 'a' both referring to the same array of type A ?.

At line labelled //3: ClassCastException is thrown. Isn't this code is just same as the code just right above it at line 17 ?.



 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Akash Trivedi wrote:

At line labelled //1: Is 'a1' is also of type 'A' ?. I don't understand the notion of it.



At this line, you are declaring two variables, a and a1, and they are both of types reference to array of class A instances.

Akash Trivedi wrote:


At line labelled //2: Are 'a1' and 'a' both referring to the same array of type A ?.



Correct. At line 11, both the two references declared at line 5 are referring to the instance that was created at line 9.

Henry
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Akash Trivedi wrote:
At line labelled //3: ClassCastException is thrown. Isn't this code is just same as the code just right above it at line 17 ?.



Well, yes, it is similar code, but it is operating on difference references... and of course, inferring from your previous question, here is the hint (which I am speculating is your main confusion) ... are the a and a1 references still pointing to the same instance?

Henry
 
Akash Trivedi
Greenhorn
Posts: 18
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it. After (a=b;) a is referring to instance of B[] and a1 is still referring to instance of A[]. That is why we can't cast a1(Arrays of A) to type B[].
Right..? :-)
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds right to me.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!