public/private/protected的具体区别

1、public:声明公共类,公共类其他类可以调用 (其它类中也可以调用)

2、private:声明私有类,私有类自己的类可以使用(只能本类之中使用),其它类不可使用。

3、protected:protected对于子女、朋友来说,就是public的,可以自由使用,没有任何限制,而对于其他的外部class,protected就变成private。

 例如:

1.service层:

复制代码

@Service
1 public class UserService{ 2 @Override//私有的userId 3 private Object userId(int id){ 4 return null; 5 } 6 @Override//公有的username 7 public Object username(String name){ 8 return null; 9 } 10 @Override 11 public Object userAge(int age){ 12 return userId(int id); 13 } 14 }
复制代码
userAge中可以使用userId因为userId和userAge在一个类中

2.controller

复制代码
1 public class UserController{
2 @Autowired
3     private UserService userService;
4     
5     @PostMapping("/userId")
6    public Object userId(String name){
7         return userService.username(name);
8    }
9 }
复制代码

在Controller中userService.userId无法点到,因为private Object userId()是私有的调不到

文章转载于:https://www.cnblogs.com/lidar/p/10842859.html

原文地址:https://www.cnblogs.com/mailyuan/p/13402817.html