Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

object reference types

 
veda vyas sista
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ObjectRefConversion.java
1. public class ObjectRefConversion{
2. public static void main(String[] args) {
3. ClassRoom[] crooms = new ClassRoom[10];
4. Room[] rooms;
5. Lab[] labs;
6. for (int i = 0; i<5; i++) {
7. crooms[i] = new ClassRoom();
8. }
9. rooms = crooms;
10. labs = crooms; // compiler error
11. }
12. }
13.
14. interface Facilities {
15. }
16. class Room {
17. } .
18. class ClassRoom extends Room implements Facilities{
19. }
20. class Lab extends ClassRoom {
21. }


The conversion in line 9 will work because rooms and crooms are both arrays and the element type of crooms (that is, ClassRoom) is convertible to the element type of rooms (that is, Room). On the other hand, line 10 will generate a compiler error because the type of elements of array crooms (that is, ClassRoom) is not convertible to the type of elements of array labs (that is, Lab).



my doubt is why line 9 is not giving error but line 10 is giving error please explain me in detail
 
vivek kumar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are not compatible:-
The hierarchy is like Room->ClassRoom->Lab
Rule is, super class array reference can hold the subclass array type but not the reverse.
So rooms = crooms; is correct but not labs = crooms;
 
vivek kumar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are not compatible:-
The hierarchy is like Room->ClassRoom->Lab
Rule is, super class array reference can hold the subclass array type but not the reverse.
So rooms = crooms; is correct but not labs = crooms;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic