编程实现Animal类的封装,特征有:名字和毛色,要求提供打印所有特征的方法。
public class Animal {
private String name;
private String color;
public Animal() {}
public Animal(String name, String color) {
setColor(color);
setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void show() {
System.out.println("名字:"+getName()+",毛色:"+getColor());
}
}
编程实现Dog类的封装并继承自Animal类,该类的特征有:牙齿数量,要求提供打印所有特征的方法。
public class Dog extends Animal{
private int tooth;
public Dog() {
super(); //调用父类的有参构造
}
public Dog(String name, String color, int tooth) {
super(name, color); //调用父类的有参构造
setTooth(tooth);
}
public int getTooth() {
return tooth;
}
public void setTooth(int tooth) {
if (tooth > 0) {
this.tooth = tooth;
} else {
System.out.println("牙齿数量不合理!");
}
}
@Override
public void show() {
super.show();
System.out.println("牙齿数量为:"+tooth);
}
}
编程实现DogTest类,在main方法中分别使用无参和有参方式构造Dog类型对象并打印特征。
public class DogTest {
public static void main(String[] args) {
//使用无参构造方式构造Dog类型的对象
Dog d1=new Dog();
d1.show(); //null null 0
//使用有参构造方式构造Dog类型的对象
Dog d2=new Dog("小黑","白色",20);
d2.show(); //小黑 白色,20
}
}