package com.test_encapsulation;
public class encapsulation {
public static void main(String[] args) {
Person person = new Person();
person.setName("jack");
person.setAge(21);
person.setSalary(800000);
person.info();
}
}
class Person{
public String name;//名字公有
private int age;//私密年龄
private double salary;//薪水
//封装。
public String getName() {
return name;
}
public void setName(String name) {
if (name.length()>=2&&name.length()<=6)//设置名字权限
this.name = name;
else
System.out.println("名字过长!");
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age>0&&age<200)//年龄权限
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 void info(){
System.out.println(name+age+salary);
}
}
package com.test_encapsulation;
public class encapsulation {
public static void main(String[] args) {
Person person = new Person("simt",20,80000);//构造器版本
person.info();
// person.setName("jack");
// person.setAge(21);
// person.setSalary(800000);
// person.info();
}
}
class Person{
public String name;
private int age;
private double salary;
public Person(String name,int age,double salary)
{
this.name=name;
this.age=age;
this.salary=salary;
//为了使我们在封装写的条件有用,可以在构造器中调用他们
setName(name);
setAge(age);
setSalary(salary);
}
public String getName() {
return name;
}
public void setName(String name) {
if (name.length()>=2&&name.length()<=6)
this.name = name;
else
System.out.println("名字过长!");
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age>0&&age<200)
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 void info(){
System.out.println(name+age+salary);
}
}