• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array Object Question  RSS feed

 
Edward Lawrence
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following 3 classes Animal, Dog, and Array in 3 separate files, I compiled them and ran only the Array class with
the following results:
line 42 output: protected Animal instance variable i = 1
line 46 output: Dog element = pkgb.Dog@45a877

My Questions:
1. Why wouldn't line 48 compile without the cast when line 42 did not need one?
2. why does line 50 produce a compile error without the "//" but line 42 seems to run the
Dog initialization block without errors?


 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Edward Lawrence wrote:1. Why wouldn't line 48 compile without the cast when line 42 did not need one?

Because one is upcasting and the other is downcasting.

2. why does line 50 produce a compile error without the "//" but line 42 seems to run the Dog initialization block without errors?

Because Animal's "i" is protected, which means it can only be accessed from subclasses of Animal or classes in the same package as Animal. Since your Array class is neither it cannot access dog.i.
 
Edward Lawrence
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is just to very and understand better.
When I created the reference in the array to the Dog object I was implicitly downcasting. Am I correct?

Another clarification / Question
So what is the function of the element I am using on line 48 to create the new Dog object?
Does that element point to a Dog or in reality to an Animal?
In other words I do not quite understand the statement on line 48 although I authored it. Please elaborate a little more for
greenhorn Edward Lawrence.
 
Edward Lawrence
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just wanted to add this if I remember correctly. When compiling, the compiler thinks sees the element as an Animal and not a Dog. Am I correct?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!