抽象結合例項 Employee

DemoLiQi發表於2024-06-23

總的抽象類Employee
在總的類裡定義私有變數,提供介面,構造無參方法,相當於構造一個javabean
public abstract class Employee {
private String name;
private int id;
public Employee(){
}

public Employee(String name, int id) {
    this.name = name;
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}
public abstract void work();

}
子類繼承父類Developer類
public abstract class Developer extends Employee {
}
Maintainer類
public abstract class Maintainer extends Employee {
}
再有子類繼承父類 這時有具體的成員方法 所以不是抽象類,但是要重寫父類的方法
繼承Developer類的Javaee類和Android類
public class Javaee extends Developer {
@Override
public void work() {
System.out.println("員工號為:"+getId()+"的"+getName()+"正在開發網站");
}
}
public class Android extends Developer{
@Override
public void work() {
System.out.println("員工號為:"+getId()+"的"+getName()+"正在開發App ");
}
}
繼承Maintainer類的Network和Hardware類
public class Network extends Maintainer{
@Override
public void work() {
System.out.println("員工號為:"+getId()+"的"+getName()+"正在開發網路");
}
}

public class Hardware extends Maintainer {
@Override
public void work() {
System.out.println("員工號為:"+getId()+"的"+getName()+"正在開發硬體");
}
}
測試類Test
public class Test {
public static void main(String[] args) {
Javaee javaee=new Javaee();
javaee.setName("李琦");
javaee.setId(1);
Android android=new Android();
android.setName("淡萌");
android.setId(2);
Network network=new Network();
network.setId(3);
network.setName("張大琦");
Hardware hardware=new Hardware();
hardware.setId(4);
hardware.setName("龍奕超");
javaee.work();
android.work();
network.work();
hardware.work();
}
}

相關文章