class Demo_Animal { //创建一个测试类
public static void main(String[] args) { //加载主方法
Cat c1 = new Cat();
c1.setName("加菲");
c1.setFoot(2);
System.out.println(c1.getName()+" "+c1.getFoot());
c1.eat();
c1.Play();
System.out.println("--------------------");
Dog d1 = new Dog();
d1.setName("牧羊犬");
d1.setFoot(2);
System.out.println(d1.getName()+" "+d1.getFoot());
d1.eat();
d1.lookDoor();
}
}
class Animal { //创建父类:animal
private String name; //成员变量初始化
private int foot;
public Animal() {} //创建一个无参构造方法
public Animal(String name,int foot) { //创建一个有参构造方法
this.name = name;
this.foot = foot;
}
public void setName(String name) { //设置name
this.name = name;
}
public String getName() { //获取name
return name;
}
public void setFoot(int foot) { //设置foot
if(foot == 4) {
this.foot = foot;
} else {
System.out.println("这不是犬类,犬类都是四条腿");
}
}
public int getFoot() {
return foot;
}
public void eat() {
System.out.println("爱吃肉");
}
}
class Cat extends Animal { //创建子类 Cat
public Cat() {};
public Cat(String name,int foot) {
super(name,foot);
}
public void Play() {
System.out.println(this.getName()+"爱玩");
}
}
class Dog extends Animal {
public Dog() {};
public Dog(String name,int foot) {
super(name,foot);
}
public void lookDoor() {
System.out.println(this.getName()+"看门");
}
}
|
|