Java-访问控制修饰符
访问控制修饰符可以修饰属性,方法,构造方法,类
private:私有访问权限控制,被private修饰属性,方法,构造方法只能在本类的内部调用,外界无法访问
public class Test1 { public static void main(String[] args) { Teacher teacher=new Teacher("刘英谦",18,100000); //因为在new调用Teacher类的构造方法,然后通过类内部构造方法来访问private修饰salary teacher.salary=200000;//报错,被private修饰的属性salary,不在Teacher外界访问 teacher.age=25; } } class Teacher{ String name; int age; private double salary; Teacher(String name,int age,double salary){ this.name=name; this.age=age; this.salary=salary; } }
public class Test1 { public static void main(String[] args) { Person person=new Person("乔峰",30,"123456");//通过调用Person构造方法,通过类内部构造方法来间接访问password属性 System.out.print(person.password);//报错,main方法在Person这个类的外部,不能访问private修饰的任何方法或属性 } } class Person{ String name; int age; private String password; Person(String name,int age,String password){ this.name=name; this.age=age; this.password=password; } }
public:用public修饰属性或方法,可以被外界任意的访问
总结,一般企业开发中,属性一般用private修饰(为了提供其安全性),方法一般用public修饰,以方便外界调用
我们可以通过使用public修饰get/set方法来访问private修饰的属性
public class Test1 { public static void main(String[] args) { Student student=new Student(); student.setName("小龙女"); String name=student.getName(); System.out.println(name); } } class Student{ private String no; private String name; private int age; private int score; private String sex; private String classes; //访问:设置值,获取值 //获取值 public String getNo() { return no; } //设置值 public void setNo(String no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getClasses() { return classes; } public void setClasses(String classes) { this.classes = classes; } }