24/03/26总结

面向对象练习题:(封装,继承,多态)

封装:对象代表什么,就得封装对应的数据,并提供数据对应的行为,(把零散的数据和行为封装成一个整体:也就是我们说的对象)
继承:当封装的JavaBean类越来越多时,类里面重复的内容就越来越多,这时我们把同一类事物当中共性的内容都抽取到父类中 在这个结构中上面的是父类,下面的是子类,这就叫做继承
多态:同类型的对象,表现出的不同形态        多态的表现形式:父类类型 对象名称 = 子类对象;

练习要求:

练习思路:

狗和猫同属于一类,可以继承于父类动物(标准JavaBean),共性为年龄,颜色,吃;

猫、狗类(无参,以及父类的构造(super)):方法重写eat,以及写出其他行为

person人单独一类(标准JavaBean):定义好成员变量,以及输出要求的成员方法

测试类输出

package com.itheima.demo6多态test;

public class Animal {
    private int age;
    private String color;

    public Animal() {
    }

    public Animal(int age, String color) {
        this.age = age;
        this.color = color;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public void eat(String something){
        System.out.println("动物在吃"+something);
    }
}
package com.itheima.demo6多态test;

public class Cat extends Animal{
    @Override
    public void eat(String something) {
        System.out.println("猫在吃"+something);
    }

    public Cat() {
    }

    public Cat(int age, String color) {
        super(age, color);
    }

    public void catchMouse(){
        System.out.println("猫在抓老鼠");
    }
}
package com.itheima.demo6多态test;

public class Dog extends Animal{
    @Override
    public void eat(String something) {
        System.out.println("狗在吃"+something);
    }

    public Dog() {
    }

    public Dog(int age, String color) {
        super(age, color);
    }

    public void lookHome(){
        System.out.println("狗在看家");
    }

}
package com.itheima.demo6多态test;

public class Person {
    int age;
    String name;

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public Person() {
    }

    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 void keepPet(Animal a, String something){
        System.out.println("年龄为"+this.age+"岁的"+this.name+"养了一只"+ a.getColor()+"的动物");
        a.eat(something);
    }

}
package com.itheima.demo6多态test;

public class test {
    public static void main(String[] args) {
        Dog dg=new Dog(3,"黑色");
        Cat ct=new Cat(4,"灰色");
        Person p1 = new Person(23,"张三");
        Person p2 = new Person(33,"李四");
        p1.keepPet(dg,"骨头");
        p2.keepPet(ct,"鱼");
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值