第5题 设计Bird 、Fish类,都继承自抽象类Animal,实现其抽象方法info(),并输出他们的信息
/**
* 动物类
*/
public abstract class Animal {
private int age;
public Animal(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public abstract void info();
}
/**
* 鸟类
*/
public class Bird extends Animal {
private String color;
public Bird(int age, String color) {
super(age);
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void info() {
System.out.println("我是一只" + this.color + "的鸟\n今年" + this.getAge() + "岁了!");
}
}
/**
* 鱼类
*/
public class Fish extends Animal {
private int weight;
public Fish(int age, int weight) {
super(age);
this.weight = weight;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public void info() {
System.out.println("我是一只"+this.weight+"斤重的鱼\n今年"+this.getAge()+"岁了!");
}
}
/**
* 测试类
*/
public class Test {
public static void main(String[] args) {
Animal animal = new Bird(4,"红色");
animal.info();
Animal animal1 = new Fish(2,5);
animal1.info();
}
}
第6题 兜兜家养了两只家禽:一只鸡和一只鸭,请用面向对象思想的封装和继承的特性进行描述
/**
* 家禽类
*/
public abstract class Poultry {
private String name;//名字
private String likeFood;//喜爱食物
public Poultry(String name,String likeFood) {
super();
this.name = name;
this.likeFood = likeFood;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLikeFood() {
return likeFood;
}
public void setLikeFood(String likeFood) {
this.likeFood = likeFood;
}
public abstract void show();
}
/**
* 鸡类
*/
public class Chicken extends Poultry {
private String strain; //品种
public Chicken(String name, String likeFood, String strain) {
super(name, likeFood);
this.strain = strain;
}
public String getStrain() {
return strain;
}
public void setStrain(String strain) {
this.strain = strain;
}
public void crow() {
System.out.println("我会打鸣!");
}
public void show() {
System.out.println("我叫"+this.getName()+",是一只"+this.strain+"!\n我喜欢吃"+this.getLikeFood()+"!");
this.crow();
}
}
/**
* 鸭类
*/
public class Duck extends Poultry {
private String type;//类型
public Duck(String name, String likeFood, String strain) {
super(name, likeFood);
this.type = strain;
}
public String getStrain() {
return type;
}
public void setStrain(String strain) {
this.type = strain;
}
public void crow() {
System.out.println("我会游泳!");
}
public void show() {
System.out.println("我叫" + this.getName() + ",是一只" + this.type + "!\n我喜欢吃" + this.getLikeFood()+"!");
this.crow();
}
}
/**
* 测试类
*/
public class PoultryTest {
public static void main(String[] args) {
Poultry poultry = new Chicken("喔喔", "虫子", "芦花鸡");
poultry.show();
System.out.println("");
Poultry poultry1 = new Duck("嘎嘎", "小鱼虾", "斑嘴鸭");
poultry1.show();
}
}