动物类:姓名,年龄,吃饭,睡觉(吃饭和睡觉属于共性功能)
猫和狗
动物培训接口:跳高(扩展功能)
案例
class test {
public static void main(String[] args) {
Cat c = new Cat("xiaohua",10);
System.out.println(c.getName() + "..." + c.getAge());
c.eat();
c.sleep();
System.out.println("-----------------------");
JumpCat jc = new JumpCat("小花",20); //如果在JumpCat类没有写有参构造方法,程序会报错,"无法将类 JumpCat中的构造器 JumpCat应用到给定类型"
System.out.println(jc.getName() + "..." + jc.getAge());
jc.eat();
jc.sleep();
jc.jump();
System.out.println("---------------------------");
Dog d = new Dog("xiaogou",30);
System.out.println(d.getName() + "..." + d.getAge());
d.eat();
d.sleep();
System.out.println("-----------------------");
JumpDog jd = new JumpDog("小狗",40);
System.out.println(jd.getName() + "..." + jd.getAge());
jd.eat();
jd.sleep();
jd.jump();
}
}
abstract class Animal {
private String name;
private int age;
public Animal() { }
public Animal(String name,int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public abstract void eat();
public abstract void sleep();
}
interface Jumping {
public void jump();
}
class Cat extends Animal {
public Cat() {}
public Cat(String name,int age) {
super(name,age);
}
public void eat() {
System.out.println("猫吃鱼");
}
public void sleep() {
System.out.println("猫睡觉");
}
}
class JumpCat extends Cat implements Jumping {
public JumpCat() {}
public JumpCat(String name,int age) {
super(name,age);
}
public void jump() {
System.out.println("猫跳高");
}
}
class Dog extends Animal{
public Dog() {}
public Dog(String name,int age) {
super(name,age);
}
public void eat() {
System.out.println("狗吃饭");
}
public void sleep() {
System.out.println("狗睡觉");
}
}
class JumpDog extends Dog implements Jumping{
public JumpDog() {}
public JumpDog(String name,int age) {
super(name,age);
}
public void jump() {
System.out.println("狗跳高");
}
}
|
|