如果一个孩子他的某些特征继承于父亲,某些特征继承于母亲(假设发色继承父亲,肤色继承母亲),该如何使用extends来编写代码呢?
目录
1.创建父类Human,抽取共性
public class Human{
String haircolor;
String skincolor;
public String getHaircolor() {
return haircolor;
}
public void setHaircolor(String haircolor) {
this.haircolor = haircolor;
}
public String getSkincolor() {
return skincolor;
}
public void setSkincolor(String skincolor) {
this.skincolor = skincolor;
}
}
如何自动生成set和get方法?
Human类右键->source->Generate getters and setters->勾选 haircolor 和 skincolor
2. 子类:在构造函数中指定父母
public class Child extends Human{
private final Human father;
private final Human mother;
public Child (Human father,Human mother){
this.father=father;
this.mother=mother;
}
public String getSkincolor(){
return mother.getSkincolor();
}
public String getHaircolor(){
return father.getHaircolor();
}
}
3.实例化
public class Test {
public static void main(String args[]){
Human wq=new Human();
Human xl=new Human();
wq.setHaircolor("黑色");
xl.setSkincolor("棕色");
wq.setSkincolor("黑色");
xl.setSkincolor("白色");
Child wxm=new Child(wq,xl);
System.out.println("孩子的发色:"+wxm.getHaircolor());
System.out.println("孩子的肤色:"+wxm.getSkincolor());
}
}
运行结果为:
孩子的发色:黑色
孩子的肤色:白色