属性私有化,使用private关键字。
照Java的开发标准而言,外部要想操作私有属性,需要按照如下形式定义操作方法:setter、getter:
setter(private String name):public void setName(String n);
getter(private String name):public String getName();
举例:
class Employee {// 雇员类
private int number ;
private String name ;
private String job ;
private double salary ;
private double income ;
private String phoneNumber;
private String address;
public Employee(int number, String name, String job, double salary, double income,String phoneNumber,String address) {
// TODO Auto-generated constructor stub
this.number=number;
this.name=name;
this.job=job;
this.salary=salary;
this.income=income;
this.phoneNumber=phoneNumber;
this.address=address;
}
public int getNumber() {
return number;
}
public void setNumber() {
this.number = number;
}
public String getName() {
return name;
}
public void setName() {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob() {
this.job = job;
}
public double getSalary(){
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double salary() {
return salary+income;
}
public double income() {
return this.salary()*12;
}
public String getInfo(){
return "雇员信息:"+"\n"+
"|编号:"+this.getNumber()+"\n"+
"|姓名:"+this.getName()+"\n"+
"|职位:"+this.getJob()+"\n"+
"|工资:"+this.getSalary()+"\n"+
"|佣金:"+this.getIncome()+"\n"+
"|月薪:"+this.salary()+"\n"+
"|年薪:"+this.income()+"\n"+
"|电话:"+this.getPhoneNumber()+"\n"+
"|地址:"+this.getAddress()+"\n";
}
}
public class Demo {
public static void main(String[] args) {
Employee Employee=new Employee(10001,"李白","Java开发工程师",20000.0,5000.0,"18888888888","长安");
System.out.println(Employee.getInfo());
}
}
运行结果:
雇员信息:
|编号:10001
|姓名:李白
|职位:Java开发工程师
|工资:20000.0
|佣金:5000.0
|月薪:25000.0
|年薪:300000.0
|电话:18888888888
|地址:长安
以后在进行开发的时候,如果有需要,则在setter上加入一些验证措施,而getter方法只是简单的将数据返回即可,不需要做任何的验证。
疑问?为什么有些没有在程序之中使用getter()方法?
在类之中的属性定义setter、getter操作方法目的就是为了设置和取得属性的内容,也许某一个操作暂时不使用到取得的操作,不过从开发来讲,必须全部提供。 以后在定义类的时候,所有的属性都要编写private封装,封装之后的属性如果需要被外部操作,则编写setter、getter。