I am sorry to say but your second point it not correct..see this from K & B
a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package.
Guess again!
I am right,
test it with the first fix I suggested applied and you will see the following error:
saySomething() has protected access in chapters.p1.Animal
The reason is that in the main method a new instance of Animal is declared. It is not part of the super/sub-class relationship that is established in creation of the Cow class, and therefore the rule applies.
e.g.
public static void main(
String [] args)
{
Animal heyAnimal = new Animal();
TestPoly.Cow c = new TestPoly().new Cow();
// remaining code here
}
Secondly, remember the main is not part of the class instaniation, the method is part of its class and not part of objects (as are all static methods), it is there mainly to provide a command line accessor to the class, and therefore has no infuence or involvement in the relations that exists here. In fact all static methods a class don't even need to reference an instansiation of the class it is part of (Though is would make logical sence to have it refering to an instance of the class ie. an object). Heres an added twist in understanding the overriding/overloading story. If Cow did not override the saySomething() method then c.saySomething(); in the main method would also through the same error message at compile time. Only code internally to the non-static methods and constructs would have access.
Lastly a part that I missed out mentioning is related to the class casting
e.g. heyAnimal=c;
As a result of this implicit class casting, you will end up lossing the use of all the methods provided in the sub-class(Cow) and will be running with methods provided in the Super class only. Proof of this can be see if you had created a non-overriding/overloading method in in Cow e.g.
...
protected void saySomethingAgain()
{System.out.println("jo jo jo!");}
...
and then tried using it with heyAnimal. e.g.
public static void main(String [] args)
{
Animal heyAnimal = new Animal();
TestPoly.Cow c = new TestPoly().new Cow();
heyAnimal=c;
//c.saySomething();
//heyAnimal.saySomething();
heyAnimal.saySomethingAgain();
}
The compilation will fail with the following error:
cannot find symbol method saySomethingAgain().
[ February 14, 2007: Message edited by: Quintin Stephenson ]