需求一:
员工类Employee
属性:姓名name,工号id,工资salary
行为:显示所有成员信息的方法show()
需求二:
动物类Animal
属性:姓名name,年龄age
行为:吃饭eat,睡觉sleep
需求三:
人类Person
属性:姓名name,年龄age,性别gender
行为:学习study,睡觉sleep
class Demo_4 {
public static void main(String[] args) {
//员工类实例化并传入参数
Employee e1 = new Employee("张三","c001",20000);
e1.show(); //输出方法
e1.setName("李四"); //设置姓名
e1.setId("d002"); //设置员工号
e1.setSalary(123.5); //设置工资
e1.show(); //输出方法
//动物类实例化并传参
Animal a1 = new Animal("猫",2);
a1.print(); //输出方法
a1.setName("狗"); //设置姓名
a1.setAge(4); //设置年龄
a1.print(); //输出方法
//人类实例化并传参
Person p1 = new Person("李天一",20,"男");
p1.print(); //输出方法
p1.setName("李天二"); //设置姓名
p1.setAge(25); //设置年龄
p1.setGender("女"); //设置性别
p1.print(); //输出方法
}
}
class Employee { //实例化员工类
private String name; //名字
private String id; //员工号
private double salary; //工资
public Employee(){} //无参构造
public Employee(String name,String id,double salary){ //带参构造
this.name = name;
this.id = id;
this.salary = salary;
}
public void setName(String name){ //设置姓名
this.name = name;
}
public String getName(){ //获取姓名
return name;
}
public void setId(String id){ //设置Id
this.id = id;
}
public String getId(){ //获取id
return id;
}
public void setSalary(double salary){ //设置工资
this.salary = salary;
}
public double getSalary(){ //获取工资
return salary;
}
//输出代码
public void show(){
System.out.println(getName()+" 员工号"+getId()+" 工资"+getSalary());
}
}
class Animal {
private String name;
private int age;
public Animal(){} //无参构造
public Animal(String name,int age){ //带参构造
this.name = name;
this.age = age;
}
public void setName(String name){ //设置名字
this.name = name;
}
public String getName(){ //获取名字
return name;
}
public void setAge(int age){ //设置年龄
this.age = age;
}
public int getAge(){ //获取年龄
return age;
}
public String eat(){
return "吃饭";
}
public String sleep(){
return "睡觉";
}
//输出代码
public void print(){
System.out.println(getName()+" "+getAge()+" "+eat()+","+sleep());
}
}
////人类
class Person {
private String name; //名字
private int age; //年龄
private String gender; //性别
public Person(){} //无参构造
public Person(String name,int age,String gender){ //带参构造
this.name = name;
this.age = age;
this.gender = gender;
}
public void setName(String name){ //设置姓名
this.name = name;
}
public String getName(){ //获取姓名
return name;
}
public void setAge(int age){ //设置年龄
this.age = age;
}
public int getAge(){ //获取年龄
return age;
}
public void setGender(String gender){ //设置性别
this.gender = gender;
}
public String getGender(){ //获取性别
return gender;
}
public String study(){ //学习方法
return "学习";
}
public String sleep(){ //睡觉方法
return "睡觉";
}
//打印方法
public void print(){
System.out.println("姓名:"+getName()+" 年龄:"+getAge()+" 性别:"+getGender()+" 我每天必须:"
+study()+" "+sleep());
}
}
|
|