封装的理解和好处
1.隐藏实现细节
2.可以对数据进行验证,保证安全合理
封装的实现步骤
1)将属性进行私有化private(不能直接修改属性)
2)提供一个公共类(public)set方法,用于对属性判断赋值
public void setXxx(类型 参数名){
//Xxx表示某个属性
//加入数据验证的业务逻辑
属性=参数名;
}
3)提供一个公共的类(public)get方法,用于获取属性的值
public 数据类型 getXxx(){//权限判断,Xxx某个属性
return xx;
}
构造器跟 setXxx结合
public static void main(String[] args) {
Person person=new Person("simth",200,50000);
// person.setAge(100);
// person.setName("jack");
// person.setSalary(30000);
System.out.println(person.info());
System.out.println(person.getName());
}
}
class Person{
public Person(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
setSalary(salary);
setName(name);
setAge(age);
}
public String name;
private int age;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
if (name.length()>1&&6>name.length()) {
this.name = name;
}else {
System.out.println("你的名字不符合要求,给你一个无名默认值");
this.name="无名者";
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age >1&&age<120) {
this.age =age;
}else {
System.out.println("年龄不符合规定,给默认年龄18");
this.age=18;
}
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String info(){
return " name ="+name+" age="+age+" salary= "+salary;
}