- class Test_Animal {
- public static void main(String[] args) {
- Cat c = new Cat("加菲",3);
- c.eat();
- c.sleep();
- System.out.println("---------------------------");
- JumpCat jc = new JumpCat("玛莎",4);
- jc.eat();
- jc.sleep();
- jc.jump();
- System.out.println("---------------------------");
- Dog d = new Dog("哈巴",6);
- d.eat();
- d.sleep();
- System.out.println("---------------------------");
- JumpDog jd = new JumpDog("藏獒",5);
- jd.eat();
- jd.sleep();
- jd.jump();
- System.out.println("---------------------------");
- }
- }
- /*
- * A:案例演示
- * 动物类:姓名,年龄,吃饭,睡觉。
- * 猫和狗
- * 动物培训接口:跳高
- */
- abstract class Animal {
- private String name; //属性name
- private int age; //属性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(); //抽象方法eat
- public abstract void sleep(); //抽象方法sleep
- }
- interface Jumping { //动物调高接口
- public abstract void jump();
- }
- class Cat extends Animal {
- public Cat() {} //空参构造
- public Cat(String name,int age) { //有参构造
- super(name,age);
- }
- public void eat(){ //重写eat方法
- System.out.println("我是" + this.getName() + ",我吃鱼,今年" + this.getAge() + "岁!");
- }
- public void sleep() { //重写父类sleep方法
- System.out.println("我的白天晚上都睡!");
- }
- }
- class JumpCat extends Cat implements Jumping {
- public JumpCat() {} //空参构造
- public JumpCat(String name,int age) {//有参构造
- super(name,age);
- }
- public void jump() { //重写接口中jump方法
- System.out.println("我会调高");
- }
- }
- class Dog extends Animal {
- public Dog() {} //空参构造
- public Dog(String name,int age) { //有参构造
- super(name,age);
- }
- public void eat() { //重写父类方法eat
- System.out.println("我是" + this.getName() + ",我吃肉,今年" + this.getAge() + "岁!");
- }
- public void sleep() { //重写父类方法sleep
- System.out.println("我白天睡觉,晚上看门!");
- }
- }
- class JumpDog extends Dog implements Jumping {
- public JumpDog() {} //空参构造
- public JumpDog(String name,int age) {//有参构造
- super(name,age);
- }
- public void jump() { //重写接口jump方法
- System.out.println("我是马戏团的狗,会跳高!");
- }
- }
复制代码
个人见解:类和接口以及继承的目的最终是为了简化代码,但是有好多弊端,那么什么时候该使用什么呢?不知各位有何高见!
|
|