Discussion on Java Foundation--protected access modifier

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.