This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Array Object Question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Array Object Question" Watch "Array Object Question" New topic
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?
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Array Object Question
 
Similar Threads
Please help me to get Java Certification
Accessing inherited protected instance variable question
Why doesn't polymorphism determine the output in this case?
Access Modifier Confusion
Protected in subclasses