Java继承代码案例

Java继承代码案例,不多说,直接敲代码

Animal 类

/**
 * @Author 公众号「MarkJava」
 * @Date 2020/11/9 15:08
 **/
public class Animal {
    private String name;
    private int month;
    private String species;
    public Animal() {}
    public Animal(String name, int month, String species) {
        this.name = name;
        this.month = month;
        this.species = species;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getMonth() {
        return month;
    }
    public void setMonth(int month) {
        this.month = month;
    }
    public String getSpecies() {
        return species;
    }
    public void setSpecies(String species) {
        this.species = species;
    }
    @Override
    public String toString() {
        return "Animal{" +
                "name='" + name + '\'' +
                ", month=" + month +
                ", species='" + species + '\'' +
                '}';
    }
}

Cat 类

/**
 * @Author MarkJava
 * @Date 2020/11/9 15:10
 **/
public class Cat extends Animal{
    private double weight;
    public Cat(){}

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }
    //跑步方法
    public String run(){
        return getName() + ",是一只属于" + getSpecies() + "的动物,它在奔跑中!";
    }

}

Dog 类

/**
 * @Author 公众号「MarkJava」
 * @Date 2020/11/9 15:20
 **/
public class Dog extends Animal{
    private int age;
    public Dog(){}
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    //狗会叫的方法
    public String call(){
        return getName()+ ",今年" + getAge() + "岁,它是属于" + getSpecies()+ "动物的,会旺旺地叫...";
    }
}

测试类

/**
 * @Author 公众号「MarkJava」
 * @Date 2020/11/9 15:15
 **/
public class Test {
    public static void main(String[] args) {
        //cat
        Cat cat = new Cat();
        cat.setName("白猫");
        cat.setSpecies("猫类");
        System.out.println(cat.run());
        //Dog
        Dog dog = new Dog();
        dog.setName("旺财");
        dog.setAge(2);
        dog.setSpecies("狗类");
        System.out.println(dog.call());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值