JavaSE-10.3.2【继承案例-猫和狗】
1 package day1.yppah03; 2 3 /* 4 3.2 案例-猫和狗 5 */ 6 7 public class AnimalDemo { 8 9 public static void main(String[] args) { 10 Cat c1 = new Cat(); 11 c1.setName("tom"); 12 c1.setAge(5); 13 System.out.println(c1.getName() + "," + c1.getAge()); 14 c1.catchMouse(); 15 16 Cat c2 = new Cat("tom", 3); 17 System.out.println(c2.getName() + "," + c2.getAge()); 18 c2.catchMouse(); 19 20 Dog d1 = new Dog(); 21 d1.setName("wangcai"); 22 d1.setAge(2); 23 System.out.println(d1.getName() + "," + d1.getAge()); 24 d1.lookDoor(); 25 26 Dog d2 = new Dog("small black", 3); 27 System.out.println(d2.getName() + "," + d2.getAge()); 28 d2.lookDoor(); 29 } 30 31 }
1 package day1.yppah03; 2 3 public class Animal { 4 5 private String name; 6 private int age; 7 8 public Animal() { 9 } 10 11 public Animal(String name, int age) { 12 this.name = name; 13 this.age = age; 14 } 15 16 public void setName(String name) { 17 this.name = name; 18 } 19 20 public void setAge(int age) { 21 this.age = age; 22 } 23 24 public String getName() { 25 return name; 26 } 27 28 public int getAge() { 29 return age; 30 } 31 32 }
1 package day1.yppah03; 2 3 public class Cat extends Animal{ 4 5 public Cat() { 6 } 7 8 public Cat(String name, int age) { 9 super(name, age); 10 } 11 12 public void catchMouse(){ 13 System.out.println("猫抓老鼠"); 14 } 15 16 }
1 package day1.yppah03; 2 3 public class Dog extends Animal{ 4 5 public Dog() { 6 } 7 8 public Dog(String name, int age) { 9 super(name, age); 10 } 11 12 public void lookDoor(){ 13 System.out.println("狗看门"); 14 } 15 16 }