黑马程序员技术交流社区

标题: 继承-猫狗案例 [打印本页]

作者: MichaelLian    时间: 2016-4-14 23:49
标题: 继承-猫狗案例

  1. class Test_Animal {
  2.         public static void main(String[] args) {
  3.                 Animal d=new Dog("Miky",3);
  4.                 d.show();
  5.                 System.out.println(d.getName()+"---"+d.getAge());
  6.                 d.eat();

  7.                 Animal c=new Cat("Coffee",1);
  8.                 c.eat();
  9.                 c.show();

  10.                 Dog dog=(Dog)d;
  11.                 dog.lookHome();
  12.         }
  13. }

  14. abstract class Animal{
  15.         private String name;
  16.         private int age;

  17.         public Animal(){}
  18.         public Animal(String name,int age){
  19.                 this.name=name;
  20.                 this.age=age;
  21.         }

  22.         public void setName(String name){
  23.                 this.name=name;
  24.         }
  25.         public String getName(){
  26.                 return name;
  27.         }

  28.         public void setAge(int age){
  29.                 this.age=age;
  30.         }
  31.         public int getAge(){
  32.                 return age;
  33.         }

  34.         public void show(){
  35.                 System.out.println("name :"+name+"---"+"age :"+age);
  36.         }

  37.         public abstract void eat();
  38. }

  39. class Cat extends Animal{
  40.         public Cat(){}
  41.         public Cat(String name,int age){
  42.                 super(name,age);
  43.         }

  44.         public void eat(){
  45.                 System.out.println("Cat eat fish!");
  46.         }

  47.         public void catchMouse(){
  48.                 System.out.println("Cat catch mouse!");
  49.         }
  50. }

  51. class Dog extends Animal{
  52.         public Dog(){}
  53.         public Dog(String name,int age){
  54.                 super(name,age);
  55.         }

  56.         public void eat(){
  57.                 System.out.println("Dog eat meat!");
  58.         }

  59.         public void lookHouse(){
  60.                 System.out.println("Dog look house!");
  61.         }
  62. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2