| Author |
Array Object Question
|
Edward Lawrence
Greenhorn
Joined: Apr 02, 2010
Posts: 21
|
|
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?
|
Regards,
Edward
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Edward Lawrence
Greenhorn
Joined: Apr 02, 2010
Posts: 21
|
|
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
Joined: Apr 02, 2010
Posts: 21
|
|
|
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?
|
 |
 |
|
|
subject: Array Object Question
|
|
|