1、Animal(动物类-父类)
package cn.nnxy.animal;
public class Animal {
private String name;
private Integer legNum;
public void shout() {
System.out.print(name + "有" + legNum + "条腿" + "叫声");
}
public Animal(String name,Integer legNum) {
setName(name);
setLegNum(legNum);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLegNum() {
return legNum;
}
public void setLegNum(Integer legNum) {
this.legNum = legNum;
}
}
2、Cat(猫类-子类)
package cn.nnxy.animal;
public class Cat extends Animal{ //继承Animal父类
public Cat(String name, Integer legNum) {
super(name, legNum);
setName(name);
setLegNum(legNum);
}
public void shout() {
System.out.print(getName() + "有" + getLegNum() + "条腿\n");
}
}
3、Duck(鸭子类-子类)
package cn.nnxy.animal;
public class Duck extends Animal{
public Duck(String name, Integer legNum) {
super(name, legNum);
setName(name);
setLegNum(legNum);
}
public void shout() {
System.out.print(getName() + "有" + getLegNum() + "条腿");
}
}
4、测试类
package test;
import cn.nnxy.animal.Animal;
import cn.nnxy.animal.Cat;
import cn.nnxy.animal.Duck;
public class Test {
public static void main(String[] args) {
Animal animal;
animal = new Cat("猫", 4);
animal.shout();
animal = new Duck("鸭子", 2);
animal.shout();
}
}
运行结果: