java创建父类,将属性封装

//创建一个 Animal 类 作为父类
包含的属性:种类,年龄,名字,食物 属性要封装起来,然后创建
getters和setters方法
// 包含的行为:声音,睡觉(时间),运动

// 创建一个 企鹅类,创建一个 狐狸类 继承Animal类//并实现两个对象的创建

img

import java.util.*;
public class Solution {
    public static void main(String[] args) {
        Penguins penguins = new Penguins("帝企鹅",10,"小帝","磷虾");
        penguins.voice();
        penguins.move();
        penguins.sleep(20);

        System.out.println("-------------------------");
        Foxes foxes = new Foxes("九尾妖狐", 11, "九尾", "野兔");
        foxes.voice();
        foxes.move();
        foxes.sleep(10);

    }

}

// 父类 Animal
class Animal{
    private String type;
    private int age;
    private String name;
    private String food;

    public Animal() {
    }

    public Animal(String type, int age, String name, String food) {
        this.type = type;
        this.age = age;
        this.name = name;
        this.food = food;
    }


    public void voice(){
        System.out.println("voice.....");
    }

    public void sleep(int time){
        System.out.println("睡"+time+"分钟");
    }

    public void move(){
        System.out.println("运动中...");
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    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 String getFood() {
        return food;
    }

    public void setFood(String food) {
        this.food = food;
    }

}

// 创建一个 企鹅类,创建一个 狐狸类 继承Animal类//并实现两个对象的创建
class Penguins extends Animal{

    public Penguins() {
        super();
    }

    public Penguins(String type, int age, String name, String food) {
        super(type, age, name, food);
    }

    @Override
    public void voice() {
        System.out.println("企鹅叫....");
    }
}

class Foxes extends Animal{
    public Foxes() {
        super();
    }

    public Foxes(String type, int age, String name, String food) {
        super(type, age, name, food);
    }

    @Override
    public void voice() {
        System.out.println("狐狸叫....");
    }
}