Department类(父类)
//部门类(父类)
public class Department{
private String name;//部门名称
private String manager;//管理者
private String responsibility;//职责
//getter/setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
public String getResponsibility() {
return responsibility;
}
public void setResponsibility(String responsibility) {
this.responsibility = responsibility;
}
//构造函数
public Department(String name,String manager,String responsibility) {
this.name = name;
this.manager = manager;
this.responsibility = responsibility;
}
//显示基本信息
public void showDetail() {
System.out.println("部门名称:"+name+"\n管理者:"+manager+"\n部门职责:"+responsibility);
}
//重写Object的equals方法,当部门名称,经理名称,部门职责相同时认为是一个部门
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj == null) {
return false;//为空false
}
if(this == obj) {
return true;//特殊情况,两个实例只有一个属性,则可以使用==
}
if(!(obj instanceof Department)) {
return false;//判断两个对象是否都是Department的实例
}
Department dm = (Department)obj;//obj强转为dm,防止obj中的内容被改变
if(this.name.equals(dm.name) && this.manager.equals(dm.manager) && this.responsibility.equals(dm.responsibility)) {
return true;
}else {
return false;
}
}
}
ResearchDept类(子类)
//研发部门,子类
public class ResearchDept extends Department{
private String researchProject; //研究项目
//子类构造函数
public ResearchDept(String name,String manager,String responsibility,String researchProject) {
//调用父类的构造方法,必须放在构造函数的第一行,super()
super(name,manager,responsibility);
this.researchProject = researchProject;
}
//子类写父类拥有的方法时,重写父类方法(Source -> Override)
public void showDetail() {
// TODO Auto-generated method stub
super.showDetail();
System.out.println("研发产品:"+this.researchProject);
}
}
main
public class text {
public static void main(String[] args) {
// TODO Auto-generated method stub
ResearchDept R1 = new ResearchDept("研发部","张三","研发产品","手机APP");
R1.showDetail();
//Object中equals的使用
ResearchDept R2 = new ResearchDept("研发部","张三","研发产品","操作系统");
if(R2.equals(R1))
System.out.println("二者是一个部门");
else
System.out.println("二者不是一个部门");
}
}