The subclass inherits the parent class and reloads the protected method to raise the access permission to public.

Source: Internet
Author: User

This tutorial introduces how to overload the protected method after the subclass inherits the parent class to Improve the access permission to the public method. If you need this method, try it.

A car company has a new car on the market, but the company requires that the car must be driven by internal staff, that's it.

The Code is as follows: Copy code

Public class NewCar {

Protected void drive (){
// Drive the car
}
}

However, if you say that I have bought a car, you cannot let people in this car company drive for me. Therefore, the driving function of this car should be open to me. Of course, I can only do this for my car, so

The Code is as follows: Copy code

Class MyNewCar extends NewCar {

@ Override
Public void drive (){
// Do my own drive
}

}

In this way, my own car will allow anyone to drive, including lending it to my friends or giving it to my girlfriend (they may want you to drive her for a ride)

The Code is as follows: Copy code
NewCar car = new NewCar ();
Car. drive (); // no. This car is not mine and cannot be opened at will
MyNewCar myCar = new MyNewCar ();
MyCar. drive (); // OK. Don't overspeed ~

Therefore, the java design can improve the permission so that the subclass can decide whether its method can be opened to the caller. Of course, if you give the public method of the original parent class to protected, sorry, the compilation fails. The reason is obvious, for example:

The Code is as follows: Copy code
NewCar car = new MyNewCar ();
Car. drive ();//

This is my car. Why can't I drive it? Sorry, do you have any evidence -_-#

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.