In depth understanding based on Java protected

  • 2020-04-01 02:00:26
  • OfStack

When it comes to the access control character protected, even beginners are confident that they have no problem understanding it. Well, let's ask a question and see...

Look at the code at both ends below, where both the cat and mouse in package B inherit from the animal class.

//Code 1: package A has an animal class & NBSP;
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 rats & NBSP;
package testb;  
import testa.Animal;  
class Cat extends Animal{  

}  
class Rat extends Animal{  
    public void crowl(){  
                crowl("zhi zhi"); //No problem, it inherits the protected method in Animal -- crowl(String)& PI;
            Cat cat=new Cat();  
                cat.crowl("miao miao"); //wrong, The method crowl(String) from the type Animal is not visible  
    }  
}  

Since both cats and mice inherit from animals, what about the crowl() method that cats inherit that can't be seen in the scope of action of rats?

The sticking point:
Protected by access rules are subtle. Although the protected field is visible to all subclasses. It is important, however, that a subclass can only access the protected domain of the parent class it inherits within its own scope, and not the protected domain that another subclass (a sibling of the same parent class) inherits. To put it bluntly: a mouse can only be called "zhi, zhi". Even if he could see the cat (he could create a cat object in his scope), he would never learn to meow.
That is, the crowl methods that cat inherits are visible within the scope of the cat class. But it is not visible within the scope of the rat class, even if rats and cats are siblings.
In addition: This is why we can't simply put aobject.clone () out when we use the clone method.

Anyway, when B extends A, within the scope of subclass B, you can only call protected methods on objects defined by subclass B (which are inherited from parent class A). You cannot call protected methods on other class A objects

Related articles: