码迷,mamicode.com
首页 > 编程语言 > 详细

java实验六(继承、接口、异常相关知识点)

时间:2017-11-02 23:11:31      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:throws   public   接口   学习   har   ring   个学生   getname   row   

定义一个学生类,定义一个大学生类和小学生类,这两个类是学生类的子类;定义一个选课接口,由大学生类实现该接口,并定义一个年龄异常处理,当小学生

年龄小于7岁时,弹出异常。

 

import java.util.Scanner;

 interface XuanKe        //选课接口
{
    void xuanKe(String xuanke);
}

class AgeException extends Exception
{
    String message;

    AgeException(int age)
    {
        message=age+"小学生年龄不能小于七岁";
    }

    public    String toString()
    {
        return message;
    }
}

class Student            //学生类
{
    static String name;
    static int age;
    static char sex;

    Student()        //默认构造器
    {

    }

    Student(String name,int age,char sex)  //定义一个可以为姓名、年龄、性别赋值的构造器
    {

        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    String getName()
    {
        return this.name;
    }

    int getAge()
    {
        return this.age;
    }

    char getSex()
    {
        return this.sex;
    }

    void sayHello()        //sayHello方法
    {
        System.out.println("好好学习,天天向上!");
    }

}

class XStudent extends Student        //定义一个小学生类,继承了学生类
{
    XStudent(String name,int age,char sex)     throws  AgeException    //定义了一个为小学生姓名、年龄、性别初始化的构造器
    {
        if(age<7)
        {
            AgeException xiaoyuqi = new AgeException(age);
            throw xiaoyuqi;
        }

        Student.name = name;
        Student.age = age;
        Student.sex = sex;
    }

    void sayHello()            //重写了sayHello方法
    {
        System.out.println("小学生应该好好学习天天向上!");
    }
}

class DStudent extends Student implements XuanKe        //定义了一个大学生类,继承了学生类并实现了接口方法
{

    DStudent(String name,int age,char sex)        //定义了一个为大学生姓名,年龄,性别初始化的构造器
    {
        Student.name = name;
        Student.age = age;
        Student.sex = sex;
    }

public  void xuanKe(String xuanke)            //实现接口中的选课方法
    {
        System.out.println("大学生"+Student.name+"选修了"+xuanke+"课");
    }

    void sayHello()        //重写父类的sayHello方法
    {
        System.out.println("大学生应该好好学习天天向上");
    }
}

public class ExStudent
{
    public static void main(String args[])
    {
       /*      DStudent daxuesheng = new DStudent("小王",20,‘男‘);
            System.out.println("请输入您的选课");
            Scanner reader = new Scanner(System.in);
            String    xuanke=reader.nextLine();
            daxuesheng.xuanKe(xuanke);   */

            try
            {
                XStudent xiaoxuesheng = new XStudent("小张",6,‘女‘);
                xiaoxuesheng.sayHello();
            }
            catch(AgeException e)
            {
                System.out.println(e.toString());
            }
    }
}

java实验六(继承、接口、异常相关知识点)

标签:throws   public   接口   学习   har   ring   个学生   getname   row   

原文地址:http://www.cnblogs.com/1473rg/p/7774991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!