【PTA】7-3 定义接口(Biology、Animal)、类(Person)、子类(Pupil)

7-3 定义接口(Biology、Animal)、类(Person)、子类(Pupil)(分数 30)
(1)定义Biology(生物)、Animal(动物)2个接口,其中Biology声明了抽象方法breathe( ),Animal声明了抽象方法eat( )sleep( )
(2)定义一个类Person(人)实现上述2个接口,实现了所有的抽象方法,同时自己还有一个方法think( )。breathe()、eat()、sleep()、think()四个方法分别输出:
我喜欢呼吸新鲜空气
我会按时吃饭
早睡早起身体好
我喜欢思考

(3)定义Person类的子类Pupil(小学生),有私有的成员变量school(学校),公有的成员方法setSchool( )、getSchool( ) 分别用于设置、获取学校信息。
(4)在测试类Main中,用Pupil类创建一个对象zhangsan。尝试从键盘输入学校信息给zhangsan,获取到该信息后输出该学校信息,格式为“我的学校是XXX”;依次调用zhangsan的breathe()、eat()、sleep()、think()方法。

输入格式:

从键盘输入一个学校名称(字符串格式)

输出格式:

第一行输出:我的学校是XXX(XXX为输入的学校名称)
第二行是breathe()方法的输出
第三行是eat()方法的输出
第四行是sleep()方法的输出
第五行是think()方法的输出

输入样例:

在这里给出一组输入。例如:

新余市逸夫小学

输出样例:

在这里给出相应的输出。例如:

我的学校是新余市逸夫小学
我喜欢呼吸新鲜空气
我会按时吃饭
早睡早起身体好
我喜欢思考

import java.util.Scanner;
//定义两个接口
interface Biology {
    void breathe();   //定义一个抽象方法
}

interface Animal {
    void eat();   //定义两个抽象方法
    void sleep();
}

class Person implements Biology,Animal {   //实现上述接口
    public Person() {
        
    }   //实现所有抽象方法
    public void breathe() {
        System.out.println("我喜欢呼吸新鲜空气");
    }
    public void eat() {
        System.out.println("我会按时吃饭");
    }
    public void sleep() {
        System.out.println("早睡早起身体好");
    }
    public void think() {
        System.out.println("我喜欢思考");
    }
}

class Pupil extends Person {   //定义Person子类Pupil
    private String school;
    public Pupil() {
        
    }
    public Pupil(String school) {
        this.school=school;
    }
    public void setSchool() {
        this.school=school;
    }
    public String getSchool() {
        return school;
    }
}

public class Main {
    public static void main(String [] args) {
        Scanner sc=new Scanner(System.in);
        Pupil zhangsan=new Pupil(sc.next());
        System.out.println("我的学校是"+zhangsan.getSchool());   //注意:私有属性通过getSchool()方法获取
        zhangsan.breathe();
        zhangsan.eat();
        zhangsan.sleep();
        zhangsan.think();
    }
}

你可能感兴趣的:(PTA题目,java)