请使用代码描述:
2岁的红色的公鸡会吃饭(啄米)和打鸣
1岁的黑色的鸭子会吃饭(吃鱼)和游泳.
提示: 把公鸡和鸭子的共性抽取家禽类中,家禽类不使用抽象类
代码实现:
[Java] 纯文本查看 复制代码 /* 1.定义家禽类(Poultry)
i.成员变量(私有): 颜色(color),年龄(age)
ii.成员方法: 吃饭(void eat())
1.输出格式: 2岁的红色家禽在吃饭
iii.提供空参和带参构造方法
iv.提供setXxx和getXxx方法*/
public class Poultry {
private String color;
private int age;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Poultry() {
// TODO Auto-generated constructor stub
}
public Poultry(String color,int age) {
this.color = color;
this.age = age;
}
public void eat() {
System.out.println(this.age+"的"+this.color+"家禽在吃饭");
}
}
/*2.定义公鸡类(Cock),继承Poultry类
i.成员方法:
1. 重写父类的 eat()方法
a)输出格式:: 2岁的红色公鸡在啄米
2. 特有方法: 打鸣(crow)
a)输出格式:: 2岁的红色公鸡在打鸣
ii.提供空参和带参构造方法*/
public class Cock extends Poultry{
public Cock() {
// TODO Auto-generated constructor stub
}
public Cock(String color,int age) {
this.setColor(color);
this.setAge(age);
}
public void eat() {
System.out.println(this.getAge()+"的"+this.getColor()+"公鸡在啄米");
}
public void crow() {
System.out.println(this.getAge()+"的"+this.getColor()+"公鸡在打鸣");
}
}
/*3.定义鸭子类(Duck),继承Poultry类
i.成员方法:
1. 重写父类的 eat()方法
a)输出格式: 1岁的黑色的鸭子在吃鱼
2. 特有方法: swim() 游泳方法
a)输出格式: 1岁的黑色的鸭子在游泳
提供空参和带参构造方法*/
public class Duck extends Poultry{
public Duck() {
// TODO Auto-generated constructor stub
}
public Duck(String color,int age) {
this.setColor(color);
this.setAge(age);
}
public void eat() {
System.out.println(this.getAge()+"的"+this.getColor()+"鸭子在吃鱼");
}
public void swim() {
System.out.println(this.getAge()+"的"+this.getColor()+"鸭子在游泳");
}
}
/* c)提供main方法
d)在main方法中
i.创建公鸡对象c,并把颜色赋值为”红色”,年龄赋值为2
ii.调用公鸡对象c的吃饭方法
iii.调用公鸡对象c的打鸣方法
iv.创建鸭子对象 d,并把颜色赋值为”黑色”,年龄赋值为1.
v.调用鸭子对象 d 的吃饭方法
调用鸭子对象 d 的游泳方法*/
public class Test {
public static void main(String[] args) {
Cock c = new Cock("红色", 2);
c.eat();
c.crow();
Duck d = new Duck("黑色", 1);
d.eat();
d.swim();
}
} |