设计Bird(鸟类)、Fish(鱼类),都继承自Animal(动物)类,实现其方法printInfo(),输出信息。
参考输出结果如图。
父类Animal代码如下:
/**
* Author:Xu Zheng Wei
* E-mail:2518298846@qq.com
* 程序功能:定义父类。
*/
package diqizhang;
/**
* 动物类,父类。
*/
public class Animal {
private int age = 0;//年龄
/**
* 不带参数的构造方法。
*/
public Animal() {
}
/**
* 带参数的构造方法 。
*/
public Animal(int age) {
this.age = age;
}
/**
* 获取年龄 。
*/
public int getAge() {
return age;
}
/**
* 设置年龄。
*/
public void setAge(int age) {
this.age = age;
}
/**
* 输出信息。
*/
public void info(){
System.out.println("我今年" + this.getAge() + "岁了!");
}
}
子类Bird(鸟类)代码如下:
/**
* Author:Xu Zheng Wei
* E-mail:2518298846@qq.com
* 程序功能:定义子类(鸟类)。
*/
package diqizhang;
/**
* 鸟类,继承自动物类。
*/
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("我是一只" + color + "的鸟!");
super.info();
System.out.println();
}
}
子类Fish(鱼类)代码如下:
/**
* Author:Xu Zheng Wei
* E-mail:2518298846@qq.com
* 程序功能:定义子类(鱼类)。
*/
package diqizhang;
/**
* 鱼类,继承自动物类。
*
*/
public class Fish extends Animal {
private int weight = 4;//重量
/**
* 带参数的构造方法。
*/
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("我是一只" + weight + "斤重的鱼!");
super.info();
System.out.println();
}
}
测试代码如下:
/**
* Author:Xu Zheng Wei
* E-mail:2518298846@qq.com
* 程序功能:测试调用代码。
*/
package diqizhang;
import diqizhang.Bird;
import diqizhang.Fish;
/**
* 测试类。
*/
public class Test {
/**
* 分别创建Bird、Fish类的对象 在控制台输出对象的信息。
* @param args
*/
public static void main(String[] args) {
Bird bird = new Bird(4, "红色");
Fish fish = new Fish(2, 5);
bird.info();
fish.info();
}
}