標籤: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實驗六(繼承、介面、異常相關知識點)