抽象类:案例:猫和狗
Posted yangbocsu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了抽象类:案例:猫和狗相关的知识,希望对你有一定的参考价值。
抽象类:案例:猫和狗
需求:请采用抽象类的思想实现猫和狗的案例,并在测试类中进行测试
1 定义动物类
package com.itheima_02;
/*
抽象类
*/
public abstract class Animal {
private int age = 20;
private String name;
//无参构造方法
public Animal() {
}
//带参数构造方法
public Animal(int age, String name) {
this.age = age;
this.name = name;
}
//生成对应的get() set() 方法
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//抽象方法
public abstract void eat();
}
2 定义猫类
package com.itheima_02;
public class Cat extends Animal{
//两个构造方法
public Cat() {
}
public Cat(int age, String city) {
super(age, city);
}
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
3 定义狗类
package com.itheima_02;
public class Dog extends Animal{
//生成构造方法
public Dog() {
}
public Dog(int age, String name) {
super(age, name);
}
@Override
public void eat() {
System.out.println("狗吃骨头");
}
}
4 定义AnimalDemo类
package com.itheima_02;
public class AnimalDemo {
public static void main(String[] args) {
//
Animal a = new Cat();
a.setAge(5);
a.setName("加菲");
System.out.println(a.getName()+","+a.getAge());
a.eat();
a = new Cat(5,"加菲");
System.out.println(a.getName()+","+a.getAge());
a.eat();
Animal b = new Dog();
b.setAge(45);
b.setName("哈士奇");
System.out.println(b.getName()+","+b.getAge());
b.eat();
b = new Dog(23,"中华田园犬");
System.out.println(b.getName()+","+b.getAge());
b.eat();
}
}
以上是关于抽象类:案例:猫和狗的主要内容,如果未能解决你的问题,请参考以下文章