继承的思想实现猫和狗的案例,并在测试类中进行测试
猫和狗——共同特性都是属于动物
1. 定义动物类(Animal)
- 成员变量:姓名,年龄
- 构造方法:无参,带参
- 成员方法:get/set 方法
2. 定义猫类(Cat),继承动物类
- 构造方法:无参,带参
- 成员方法:抓老鼠(catchMouse)
3. 定义狗类(Dog), 继承动物类
- 构造方法:无参,带参
- 成员方法:看门(lookDoor)
4. 定义测试类(AnimalDemo), 写代码测试
示例代码:
AnimalParent.java
package com.面向对象.Demo14;
public class AnimalParent {
private String name; // 名称
private int age; // 年龄
public AnimalParent() {
}
public AnimalParent(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Cat.java
package com.面向对象.Demo14;
public class Cat extends AnimalParent {
public Cat() {
}
public Cat(String name, int age) {
super(name, age);
}
public void catchMouse() {
System.out.println("抓老鼠");
}
}
Dog.java
package com.面向对象.Demo14;
public class Dog extends AnimalParent {
public Dog() {
}
public Dog(String name, int age) {
super(name, age);
}
public void lookDoor() {
System.out.println("看门");
}
}
AnimalDemo01.java
package com.面向对象.Demo14;
public class AnimalDemo01 {
/**
* 使用有参构造方法给我们成员属性 赋值
*/
public static void main(String[] args) {
Cat catA = new Cat("小猫A", 3);
Cat catB = new Cat("小猫B", 3);
System.out.print(catA.getName() + "," + catA.getAge() + ",");
catA.catchMouse();
System.out.print(catB.getName() + "," + catB.getAge() + ",");
catB.catchMouse();
Dog dogA = new Dog("小狗A", 2);
Dog dogB = new Dog("小狗B", 2);
System.out.print(dogA.getName() + "," + dogA.getAge() + ",");
dogA.lookDoor();
System.out.print(dogB.getName() + "," + dogB.getAge() + ",");
dogB.lookDoor();
}
}
AnimalDemo02.java
package com.面向对象.Demo14;
public class AnimalDemo02 {
/**
* 使用 set 方法给成员属性 赋值
*/
public static void main(String[] args) {
Cat cat1 = new Cat();
cat1.setName("小猫A");
cat1.setAge(2);
Cat cat2 = new Cat();
cat2.setName("小猫B");
cat2.setAge(2);
System.out.print(cat1.getName() + "," + cat1.getAge() + ",");
cat1.catchMouse();
System.out.print(cat2.getName() + "," + cat2.getAge() + ",");
cat2.catchMouse();
Dog dog1 = new Dog();
Dog dog2 = new Dog();
dog1.setName("小狗A");
dog2.setName("小狗B");
dog1.setAge(3);
dog2.setAge(3);
System.out.print(dog1.getName() + "," + dog1.getAge() + ",");
dog1.lookDoor();
System.out.print(dog2.getName() + "," + dog2.getAge() + ",");
dog2.lookDoor();
}
}
综上:使用有参构造方法给成员属性赋值的 代码量要比 使用set方法给成员属性赋值要少,∴一般推荐使用有参构造方法给成员属性赋值。
下一篇文章:包