When it comes to access control character protected, even beginners are generally confident that they have no problem with this understanding. Well, let's ask a question to see ...
Look at the code below, where both the cat and the mouse in package B inherit the animal.
Copy Code code as follows:
//code 1: There is an animal class in package a
Package Testa;
public class Animal {
protected void Crowl (String c) {
System.out.println (c);
}
}
//code 2: There are two classes in package B--Cats and rodents
Package testb;
Import Testa. Animal;
Class Cat extends animal{
}
Class Rat extends animal{
public void Crowl () {
Crowl ("Zhi zhi"); No problem, inherited the protected method--crowl (String) in animal
Cat cat=new Cat ();
Cat.crowl ("Miao Miao"); Wrong, the method Crowl (String) from the type Animal are not visible
}
}
Since both cats and rats have inherited animals, how can the Crowl () method of cats not be seen in the sphere of rodent action?
The crux of the problem :
Protected Access protection rules are tricky. Although the protected domain is visible to all subclasses. It is important, however, that subclasses can only access the protected domain of the parent class that they inherit from within their scope, and not the protected domain inherited from the other subclasses (the half-brother of the half). To be blunt: the mouse can only be called "Zhi,zhi". Even if he can see a cat (you can create a cat object within your scope), you will never learn to bark.
In other words, the Crowl method that cat inherits is visible within the scope of the Cat class. But it is not visible in the rat sphere, even if Rat,cat is a brother.
In addition:That's why we can't simply aobject.clone the object directly when we use the Clone method.
In short, when B extends a, within the scope of subclass B, only the protected method of the object defined by the book Class B can be invoked (the method inherits from the parent Class A). Protected methods that cannot invoke other Class A objects