定义一个员工类employee,具有属性 id(String),属性姓名name(String)、年龄age(int)和薪水salary(float),函数成员包括:构造函数,设置/读取id函数setId和getId,设置/读取姓名函数setName和getName,设置/读取年龄函数setAge和getAge,设置/读取薪水函数setSalary和 getSalary,输出员工基本信息的函数print。在主函数中首先创建任一员工对象emp1最后输出 emp1 的基本信息。
代码如下:
public class Employee {
// 属性
private int id;
private String name;
private int age;
private float salary;
// 构造函数
public Employee() {
}
public Employee(int id, String name, int age, float salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
// getter and setter
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
// 输出
public void print() {
System.out.println("id = " + id + ", name = " + name + ", age = " + age + ", salary = " + salary);
}
// main
public static void main(String[] args) {
Employee emp1 = new Employee(1, "zhangsan", 18, 2000);
emp1.print();
}
}
下面是我的思路:
1、定义四个属性:id, name,age,salary
2、定义两个构造器,一个无参,一个有四个用于参数初始化类四个属性的参数
3、分别定义四个属性的get和set方法
4、定义employee类的print方法,打印四个属性的值
6、在main方法,调用带四个参数的构造器创建对象emp1, 然后调用他的print方法打印对象emp1的基本信息。
代码如下:
public class employee {
private String id;
private String name;
private int age;
private float salary;
public employee() {
}
public employee(String id, String name, int age, float salary) {
super();
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public void print() {
System.out.println( "id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary );
}
public static void main(String[] args) {
// TODO Auto-generated method stub
employee emp1 = new employee("20200102","张三",22,20000);
emp1.print();
}
}