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 -_-#