参考代码:
public class Animal { //父类
private int age;
//get set方法
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Animal() { //无参构造
super();
}
public Animal(int age) { //有参构造
super();
this.age = age;
}
//自我介绍
public String introduce(){
return "这是自我介绍的方法";
}
}
public class Bird extends Animal{ //继承
private String color;
//get set方法
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Bird() { //无参构造
super();
}
public Bird(int age, String color) { //有参构造
super(age);
this.color = color;
}
//自我介绍
public String introduce(){
return "我是一只"+color+"的鸟!\n今年"+super.getAge()+"岁了!\n"+this.fly();
}
public String fly(){
return "我展翅高翔";
}
}
public class Fish extends Animal{ //继承
private double weight;
//get set方法
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public Fish() { //无参构造
super();
}
public Fish(int age, double weight) { //有参构造
super(age);
this.weight = weight;
}
//自我介绍
public String introduce(){
return "我是一只"+weight+"斤重的鱼!\n今年"+super.getAge()+"岁了!\n"+this.swim();
}
public String swim(){
return "我在水里游泳吐泡";
}
}
public class Test { //测试类
public static void main(String[] args) {
Bird b=new Bird(4,"红色"); //创建对象
System.out.println(b.introduce()); //调用自我介绍的方法 并将String类型的结果打印输出
System.out.println("================");
Fish f=new Fish(2,5); //创建对象
System.out.println(f.introduce()); //调用自我介绍的方法 并将String类型的结果打印输出
}
}