Discussion on Java Foundation--protected access modifier
According to the official statement : ()
The protected modifier can modify the self-loss class in other packages, but I did an experiment and found an interesting phenomenon!
For details, please look down:
Package Com.demo1; Public classDemo1 {protectedDemo1 () {System. out. println ("protected"); } protected voidfunction () {System. out. println ("protected Method"); }}package Com.demo2;import Com.demo1; Public classDemo2 extends demo1{ PublicDemo2 () {super ();//calling a protected method for a parent class in a different package is established } Public Static voidMain (string[] args) {
Finaldemo f=NewFinaldemo ();//Change the Demo1 constructor to public first, or the new object will fail, prompting the constructor to be public.F.function ();//Tip This method if the public type }}
I have created 2 classes in different packages (Demo1 and Demo2), where Demo2 inherits Demo1;
1. Call the constructor of its parent class Demo1 in the Demo2 constructor ( Note: The Demo1 constructor is protected decorated ), the call succeeds, and the official statement .
2. Then change the constructor of the Demo1 class to public, then Demo2 the main function of the new Demo1 object and invoke the protected function () method of Demo1; This is the prompt function () The modifier of the method cannot be protected, but it should be changed to public, and the official statement deviates from each other.
Now I doubt slowly??? Hope that the master predecessors enlighten.
Discussion on Java Foundation--protected access modifier