upcasting: parent and child at different packages

Dear all,

I'm studying to pass SCJP and I found an example that seems to break the casting rules, of course I might be wrong, that's why I ask your help. See the following example (please don't mind synthax errors):

--Animal.java

package A;

public class Animal{

void eat(){ } // default access, visible only inside package A

}

--Dog.java

package B;

import A.Animal;

public class Dog extends Animal{ //inheritance OK, Animal is public

// it cannot override eat, not heritable (default access)

// it does not implement a eat method for itself

}

--Test.java

package A;

import B.Dog;

public class Test{

public static void main(String [ ] args){

Animal animal = new Dog(); // no casting needed

Dog dog = new Dog();

dog.eat(); // it will be a compile time error, no such method

animal.eat(); // (*)

}

}

--

(*)

At compile time no problem, becasue:

- variable animal is of type Animal which has a method eat()

- class Test is inside the same package of class Animal so method eat is visible for Test

- method eat is not abstract so it does not need to be implemented by Dog

But animal is a Dog object and as the casting is going up the inheritance tree (Dog IS-A Animal) there shouldn't be any restrictions wrt calling Animal methods or accessing its members. But as method eat is not heritable by Dog there will be a runtime exception, Dog does not know how to eat. So it's not allways safe to make upcast, I thought restrictions applied only when we have downcasting.

On the other hand, my certification book (I won't tell the name) says the following: " (...) Dog IS-A Animal, which means that anything an Animal can do, a Dog can do. A Dog can do more, of course, but the point is anyone with an Animal reference can safely call Animal methods on a Dog instance. (...)"

So I'm very very confused :o(

Thanks in advance for your help.

-Thyago Consort

[2075 byte] By [consorta] at [2007-11-27 10:57:28]
# 1

Here's a tutorial from sun that explains it a little more.

http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html

It's true that package private access doesn't allow a subclass in another package access. If you want it to be accessible, then give it public or protected access.

It's not that it breaks the casting rules, it's that your book doesn't explain the casting rules completely. That line from your cert book applies for protected or higher access only.

hunter9000a at 2007-7-29 12:09:20 > top of Java-index,Java Essentials,Training...